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 elsewhere. Obviously, I am new to Ruby.
The array. max() method in Ruby enables us to find the maximum value among elements of an array. It returns the element with the maximum value.
Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.
index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found. Syntax: str.index()
For Ruby 1.8.7 or above:
a.each_with_index.max[1]
It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max
method anyway.
In ruby 1.9.2 I can do this;
arr = [4, 23, 56, 7] arr.rindex(arr.max) #=> 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With