Reputation: 35542
I have an array of elements. If I do a arr.max
I will get the maximum value. But I would like to get the index of the array. How to find it in Ruby
For example
a = [3,6,774,24,56,2,64,56,34]
=> [3, 6, 774, 24, 56, 2, 64, 56, 34]
>> a.max
a.max
=> 774
I need to know the index of that 774
which is 2
. How do I do this in Ruby?
Upvotes: 27
Views: 24064
Reputation: 370112
In 1.8.7+ each_with_index.max
will return an array containing the maximum element and its index:
[3,6,774,24,56,2,64,56,34].each_with_index.max #=> [774, 2]
In 1.8.6 you can use enum_for
to get the same effect:
require 'enumerator'
[3,6,774,24,56,2,64,56,34].enum_for(:each_with_index).max #=> [774, 2]
Upvotes: 28