bragboy
bragboy

Reputation: 35542

How to find the index of an array which has a maximum value

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

Answers (3)

sepp2k
sepp2k

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

Raoul Duke
Raoul Duke

Reputation: 4301

that should work

[7,5,10,9,6,8].each_with_index.max

Upvotes: 7

ennuikiller
ennuikiller

Reputation: 46965

a.index(a.max)  should give you want you want

Upvotes: 33

Related Questions