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

后端 未结 6 1068
耶瑟儿~
耶瑟儿~ 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:57

    Here is a way to get all the index values of the max values if more than one.

    Given:

    > a
    => [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3]
    

    You can find the index of all the max values (or any given value) by:

    > a.each_with_index.select {|e, i| e==a.max}.map &:last
    => [7, 8]
    

提交回复
热议问题