Ruby: How to find the index of the minimum array element?

kyrylo picture kyrylo · Feb 11, 2011 · Viewed 20.3k times · Source

Is there any way to rewrite this more elegant? I think, that it's a bad piece of code and should be refactored.

>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3

Answer

andersonvom picture andersonvom · Nov 4, 2012

I believe this will traverse the array only 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