Chu*_*uck 109
对于Ruby 1.8.7或更高版本:
a.each_with_index.max[1]
Run Code Online (Sandbox Code Playgroud)
它做了一次迭代.不完全是最具语义性的东西,但是如果你发现自己做了很多,我会把它包装在一个index_of_max
方法中.
eas*_*fri 14
在ruby 1.9.2中,我可以这样做;
arr = [4, 23, 56, 7]
arr.rindex(arr.max) #=> 2
Run Code Online (Sandbox Code Playgroud)
以下是我正在考虑回答这个问题:
a = (1..12).to_a.shuffle
# => [8, 11, 9, 4, 10, 7, 3, 6, 5, 12, 1, 2]
a.each_index.max_by { |i| a[i] }
# => 9
Run Code Online (Sandbox Code Playgroud)
只是想注意此处某些解决方案的行为和性能差异。重复max 元素的“打破平局”行为:
a = [3,1,2,3]
a.each_with_index.max[1]
# => 3
a.index(a.max)
# => 0
Run Code Online (Sandbox Code Playgroud)
出于好奇,我将它们都运行了Benchmark.bm
(对于a
上述):
user system total real
each_with_index.max 0.000000 0.000000 0.000000 ( 0.000011)
index.max 0.000000 0.000000 0.000000 ( 0.000003)
Run Code Online (Sandbox Code Playgroud)
然后我生成了一个新a
的Array.new(10_000_000) { Random.rand }
并重新运行测试:
user system total real
each_with_index.max
2.790000 0.000000 2.790000 ( 2.792399)
index.max 0.470000 0.000000 0.470000 ( 0.467348)
Run Code Online (Sandbox Code Playgroud)
这让我觉得除非你特别需要选择更高的索引最大值,否则a.index(a.max)
是更好的选择。