2010-08-21 91 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] 
相關問題