有什么办法可以更优雅地重写它吗?我认为,这是一段糟糕的代码,应该重构。
>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3
我相信这只会遍历数组一次并且仍然很容易阅读:
numbers = [20, 30, 40, 50, 10] # => [20, 30, 40, 50, 10]
elem, idx = numbers.each_with_index.min # => [10, 4]
这仅遍历数组一次,而ary.index(ary.min)
将遍历它两次:
ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }
阅读其他情况(找到所有且仅最后一个最小元素)会很有趣。
ary = [1, 2, 1]
# find all matching elements' indexes
ary.each.with_index.find_all{ |a,i| a == ary.min }.map{ |a,b| b } # => [0, 2]
ary.each.with_index.map{ |a, i| (a == ary.min) ? i : nil }.compact # => [0, 2]
# find last matching element's index
ary.rindex(ary.min) # => 2
我实际上喜欢@andersonvom 的答案,它只需要循环一次数组并仍然获得索引。
如果您不想使用ary.each_with_index.min
,您可以执行以下操作:
ary = [2,3,4,5,1] # => [2,3,4,5,1]
_, index_of_minimal_value_in_array = ary.each_with_index.min # => [1, 4]
index_of_minimal_value_in_array # => 4