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

后端 未结 6 1074
耶瑟儿~
耶瑟儿~ 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条回答
  •  Happy的楠姐
    2020-12-23 10:03

    a = [1, 4 8]
    a.inject(a[0]) {|max, item| item > max ? item : max }
    

    At least it's Ruby-like :)

提交回复
热议问题