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

bra*_*boy 26 ruby arrays

我有一系列元素.如果我这样做,arr.max我将获得最大值.但我想得到数组的索引.如何在Ruby中找到它

例如

a = [3,6,774,24,56,2,64,56,34]
=> [3, 6, 774, 24, 56, 2, 64, 56, 34]
>> a.max
a.max
=> 774
Run Code Online (Sandbox Code Playgroud)

我需要知道的是,指数7742.我如何在Ruby中执行此操作?

enn*_*ler 33

a.index(a.max)  should give you want you want
Run Code Online (Sandbox Code Playgroud)

  • 这将两次通过阵列. (9认同)

sep*_*p2k 28

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

[3,6,774,24,56,2,64,56,34].each_with_index.max #=> [774, 2]
Run Code Online (Sandbox Code Playgroud)

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

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


Rao*_*uke 7

应该工作

[7,5,10,9,6,8].each_with_index.max
Run Code Online (Sandbox Code Playgroud)