Reputation: 229
Please help me to figure out min_by behaviour.
I have a "normas" table with two columns (raw_value, percentile). After some calculations I get calculated_result, and my goal is to find percentile for closest raw_value to my calculated_result. My approach as below:
raw = Norma.where(name: name).map(&:raw_value).min_by { |x| (x.to_f - value.to_f).abs }
It works, but I can't figure out all logic, here's what I mean:
arr = [1,2,3,4,5]
arr.min_by {|x| (x - 3.5).abs}
=> 3
in this case we have two identical differences (0.5 to 3 as well as to 4), so my question is what is rule for choosing result if more than one minimal found.
Have a productive day! :)
Upvotes: 0
Views: 490
Reputation: 36860
In case of equal values, the first minimum counts.
Try it with [5, 4, 3, 2, 1] and you'll see the result is now 4.
This is consistent with #index
which returns the first index position that matches a value.
Think of it as this...
temp_arr = arr.map{ |x| (x-3.5).abs }
arr[temp_arr.index(temp_arr.min)]
Upvotes: 1