[英]How to find the index of an array which has a maximum value
我有一系列元素。 如果我做了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中執行此操作?
a.index(a.max) should give you want you want
在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]
應該工作
[7,5,10,9,6,8].each_with_index.max
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.