在Ruby中,获取数组中最大值索引的最简洁方法是什么? [英] In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?
本文介绍了在Ruby中,获取数组中最大值索引的最简洁方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果 a
是数组,我想要 a.index(a.max)
,但更多Ruby -喜欢。这应该是显而易见的,但我无法在其他地方找到答案。显然,我是Ruby的新手。
If a
is the array, I want a.index(a.max)
, but something more Ruby-like. It should be obvious, but I'm having trouble finding the answer at so and elsewhere. Obviously, I am new to Ruby.
推荐答案
对于Ruby 1.8.7或更高版本:
For Ruby 1.8.7 or above:
a.each_with_index.max[1]
它进行一次迭代。不完全是最具语义性的东西,但是如果你发现自己做了很多,我会用 index_of_max
方法包装它。
It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max
method anyway.
这篇关于在Ruby中,获取数组中最大值索引的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文