我有一系列元素.如果我这样做,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)
我需要知道的是,指数774是2.我如何在Ruby中执行此操作?
enn*_*ler 33
a.index(a.max) should give you want you want
Run Code Online (Sandbox Code Playgroud)
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)