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

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


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


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

ary = [1, 2, 1]# find all matching elements' indexesary.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 indexary.rindex(ary.min) # => 2


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

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