Search code examples
rubyarraysindexingelementminimum

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


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

Solution

  • It would be interesting to read about other situations (finding all and only last minimal 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