Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to find the index of the minimum array element?

Tags:

Is there any way to rewrite this more elegant? I think, that it's a bad piece of code and should be refactored.

>> a = [2, 4, 10, 1, 13] => [2, 4, 10, 1, 13] >> index_of_minimal_value_in_array = a.index(a.min) => 3 
like image 580
kyrylo Avatar asked Feb 11 '11 00:02

kyrylo


People also ask

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.

How do you find the lowest number in an array in Ruby?

Use the min Method to Get Minimum Number in an Array in Ruby Calling min without an argument returns the minimum number ( element ) but returns the n-smallest numbers if argument "n" is passed to it.


2 Answers

I believe this will traverse the array only once and is still easy to read:

numbers = [20, 30, 40, 50, 10]           # => [20, 30, 40, 50, 10] elem, idx = numbers.each_with_index.min  # => [10, 4] 
like image 187
andersonvom Avatar answered Oct 14 '22 09:10

andersonvom


This traverses the array only once whereas ary.index(ary.min) would traverse it twice:

ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx } 
like image 24
x17y19 Avatar answered Oct 14 '22 10:10

x17y19