In Ruby, what is the cleanest way of obtaining the index of the largest value in an array? In Ruby, what is the cleanest way of obtaining the index of the largest value in an array? arrays arrays

In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?


For Ruby 1.8.7 or above:

a.each_with_index.max[1]

It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max method anyway.


In ruby 1.9.2 I can do this;

arr = [4, 23, 56, 7]arr.rindex(arr.max)  #=> 2


Here is what I am thinking to answer this question :

a = (1..12).to_a.shuffle# => [8, 11, 9, 4, 10, 7, 3, 6, 5, 12, 1, 2]a.each_index.max_by { |i| a[i] }# => 9