I'm looking for a way to find the value and index of the first occurrence of the largest element in an array (in ruby). I have not been able to find a way to achieve this with fewer than 2 lines of code and without traversing the array more than I would like.
First I tried:
example = [1, 100, 2, 100, 3]
value, index = example.each_with_index.max
But this gives me the index of the last occurrence of the largest element.
My current approach is:
example = [1, 100, 2, 100, 3]
value = example.max
index = example.find_index(value)
Which works, but if the first and last occurrences of the largest element are the last two elements of the array, my current code has to traverse pretty much the entire array twice.
I'm more interested in performance than code size, but if there is a non-wasteful one-line solution that would be great!