2010-08-21 92 views
26

我有一个元素数组。如果我做了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 

我需要知道774这是2的索引。我如何在Ruby中执行此操作?

+0

这个问题相当于在http://stackoverflow.com/questions/1656677/how-do-i-find-a-integer-max-integer-in-an-array-for-ruby- and-return-the-indexed-p – 2010-08-23 07:09:07

回答

33
a.index(a.max) should give you want you want 
+9

虽然这将通过数组两次。 – sepp2k 2010-08-21 19:56:10

+1

至少在Python中,用C语言编写的函数通过数组要快于在解释代码中更聪明一些:http://lemire.me/blog/archives/2011/06/14/the-语言解释器是新机器/ – RecursivelyIronic 2012-03-23 00:11:20

+0

是通过每个数组遍历数组,并使用比较来跟踪当前最大速度比这个解决方案更快? – srlrs20020 2017-11-30 16:23:34

6

应该工作

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

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

[3,6,774,24,56,2,64,56,34].each_with_index.max #=> [774, 2] 

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

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