TiSer TiSer - 5 months ago 31
Ruby Question

How to find indexes of max n values in array

I have an array

[0, 0, 10, 0, 3, 1]
. I want to have the indexes of max three elements from this array, which would be:
[2, 4, 5]
.

How do I do it without finding max element, delete it (make 0), then find next one, delete it and at last find third one? I can't sort this array, I need index from the current position.

Answer
a = [0, 0, 10, 0, 3, 1]
a.each_index.max_by(3){|i| a[i]} # => [2, 4, 5]

or

[0, 0, 10, 0, 3, 1].each_with_index.max(3).map(&:last) # => [2, 4, 5]
Comments