How to find the position of the maximum value in an array?

If i have

ary = [7, 8, 0, 1, nil, 6]

How to find the position of the maximum value in an array? I can do this, but it will take more than one line.

+3
source share
4 answers

This returns the index of the first maximum value in the array:

ary = [7, 8, 0, 1, nil, 6, 8]
ary.index(ary.compact.max)
=> 1 
+5
source

A little more verbose than the selected answer, but with only one traversal of the array and without intermediate arrays (assigns an arbitrary -1as the sort value for nil):

>> ary.each_with_index.max_by { |x, idx| x || -1 }[1] 
=> 1
+2
source

Something like this work?

ary.sort
ary.reverse
ary[0]
0
source

Try it.

ary = [7, 8, 0, 1, nil, 6]
puts ary.index(ary.compact.max)
0
source

All Articles