简体   繁体   中英

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?

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

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]

应该工作

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM