In Ruby, what is the cleanest way to get the index of the highest value in an array?

If a is an array, I want a.index(a.max) , but something more like Ruby. This should be obvious, but it's hard for me to find the answer anywhere else. Obviously, I am new to Ruby.

+42
arrays max ruby indexing
Jan 27 '10 at 19:47
source share
6 answers

For Ruby 1.8.7 or higher:

 a.each_with_index.max[1] 

It performs one iteration. Not exactly the semantic thing, but if you did so much, I would still index_of_max it with the index_of_max method.

+98
Jan 27 '10 at 20:02
source share

In ruby โ€‹โ€‹1.9.2, I can do this;

 arr = [4, 23, 56, 7] arr.rindex(arr.max) #=> 2 
+14
Oct 28 '11 at 11:11
source share

Here is what I think to answer this question:

 a = (1..12).to_a.shuffle # => [8, 11, 9, 4, 10, 7, 3, 6, 5, 12, 1, 2] a.each_index.max_by { |i| a[i] } # => 9 
+6
Aug 29 '15 at 18:02
source share
 a = [1, 4 8] a.inject(a[0]) {|max, item| item > max ? item : max } 

At least it looks like Ruby :)

+2
Jan 27 '10 at 20:02
source share

Here's a way to get all the index values โ€‹โ€‹of maximum values, if more than one.

Given:

 > a => [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3] 

You can find the index of all maximum values โ€‹โ€‹(or any given value):

 > a.each_with_index.select {|e, i| e==a.max}.map &:last => [7, 8] 
+1
Jul 03 '17 at 21:33
source share

I just wanted to note the differences in behavior and performance for some solutions here. Behavior "communication failure" duplicates :

 a = [3,1,2,3] a.each_with_index.max[1] # => 3 a.index(a.max) # => 0 

Out of curiosity, I spent them at Benchmark.bm (for a above):

 user system total real each_with_index.max 0.000000 0.000000 0.000000 ( 0.000011) index.max 0.000000 0.000000 0.000000 ( 0.000003) 

Then I generated a new a with Array.new(10_000_000) { Random.rand } and repeated the test:

 user system total real each_with_index.max 2.790000 0.000000 2.790000 ( 2.792399) index.max 0.470000 0.000000 0.470000 ( 0.467348) 

This makes me think if you don't need to select a higher index max, a.index(a.max) is the best choice.

+1
Dec 14 '17 at 1:44
source share



All Articles