In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?

后端 未结 6 1096
耶瑟儿~
耶瑟儿~ 2020-12-23 09:17

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

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 09:49

    Just wanted to note a behavioral and performance difference for some of the solutions here. The "tie breaking" behavior of duplicate max elements:

    a = [3,1,2,3]
    a.each_with_index.max[1]
    # => 3
    a.index(a.max)
    # => 0
    

    Out of curiosity I ran them both in Benchmark.bm (for the a above):

    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)
    

    Then I generated a new a with Array.new(10_000_000) { Random.rand } and reran the test:

    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)
    

    This makes me think unless you specifically need to choose the higher index max, a.index(a.max) is the better choice.

提交回复
热议问题