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.
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
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):
-1
nil
>> ary.each_with_index.max_by { |x, idx| x || -1 }[1] => 1
Something like this work?
ary.sort ary.reverse ary[0]
Try it.
ary = [7, 8, 0, 1, nil, 6] puts ary.index(ary.compact.max)