[ACCEPTED]-Ruby: How to find the index of the minimum array element?-minimum

Accepted answer
Score: 49

I believe this will traverse the array only 1 once and is still easy to read:

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
Score: 9

This traverses the array only once whereas 1 ary.index(ary.min) would traverse it twice:

ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }
Score: 8

It would be interesting to read about other 2 situations (finding all and only last minimal 1 element).

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
Score: 4

I actually like @andersonvom 's answer, it 3 only need to loop the array once and still 2 get the index.

And in case you don't want 1 to use ary.each_with_index.min, here is what you can do:

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

More Related questions