Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?

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.

like image 942
Cary Swoveland Avatar asked Jan 27 '10 19:01

Cary Swoveland


People also ask

How do you find the largest element in an array in 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.

How do you find the index of an element in Ruby?

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.

What is index in Ruby?

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()


2 Answers

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.

like image 94
Chuck Avatar answered Sep 17 '22 07:09

Chuck


In ruby 1.9.2 I can do this;

arr = [4, 23, 56, 7] arr.rindex(arr.max)  #=> 2 
like image 27
eastafri Avatar answered Sep 21 '22 07:09

eastafri