Ruby:如何找到最小数组元素的索引?

kyr*_*ylo 21 ruby arrays indexing element minimum

有没有办法重写这个更优雅?我认为,这是一段糟糕的代码,应该重构.

>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3
Run Code Online (Sandbox Code Playgroud)

and*_*vom 43

我相信这只会遍历数组一次并且仍然易于阅读:

ary = [2,3,4,5,1]        # => [2,3,4,5,1]
ary.each_with_index.min  # => [1, 4]
                         # where 1 is the element and 4 is the index
Run Code Online (Sandbox Code Playgroud)


小智 8

这只遍历数组一次,然后ary.index(ary.min)遍历它两次:

ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }
Run Code Online (Sandbox Code Playgroud)

  • `ary.index(ary.min)`阅读起来要简单得多. (3认同)

the*_*Man 7

阅读其他情况(找到所有并且只有最后一个最小元素)会很有趣.

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
Run Code Online (Sandbox Code Playgroud)