如何找到具有最大值的数组的索引

时间:2022-07-09 21:30:06

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

我有一个元素数组。如果我做一个arr。最大值。但是我想要得到数组的索引。如何在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?

我需要知道774的指数是2。如何在Ruby中实现这一点?

3 个解决方案

#1


33  

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

#2


26  

In 1.8.7+ each_with_index.max will return an array containing the maximum element and its index:

在1.8.7 + each_with_index。max会返回一个包含最大元素及其索引的数组:

[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:

在1.8.6中,您可以使用enum_for获得相同的效果:

require 'enumerator'
[3,6,774,24,56,2,64,56,34].enum_for(:each_with_index).max #=> [774, 2]

#3


7  

that should work

这应该工作

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

#1


33  

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

#2


26  

In 1.8.7+ each_with_index.max will return an array containing the maximum element and its index:

在1.8.7 + each_with_index。max会返回一个包含最大元素及其索引的数组:

[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:

在1.8.6中,您可以使用enum_for获得相同的效果:

require 'enumerator'
[3,6,774,24,56,2,64,56,34].enum_for(:each_with_index).max #=> [774, 2]

#3


7  

that should work

这应该工作

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