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
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.
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.
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]
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 }
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