tags:

views:

54

answers:

3

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. Is this possible at all??

+5  A: 
a.index(a.max)  should give you want you want
ennuikiller
This will go through the array twice though.
sepp2k
+3  A: 

that should work

[7,5,10,9,6,8].each_with_index.max
Raoul Duke
+6  A: 

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]
sepp2k