简体   繁体   English

Ruby Min_by逻辑

[英]Ruby min_by logic

Please help me to figure out min_by behaviour. 请帮助我找出min_by行为。

I have a "normas" table with two columns (raw_value, percentile). 我有一个包含两列(raw_value,百分位)的“标准”表。 After some calculations I get calculated_result, and my goal is to find percentile for closest raw_value to my calculated_result. 经过一些计算后,我得到了calculated_result,我的目标是找到与我的calculated_result最接近的raw_value的百分位数。 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. 在这种情况下,我们有两个相同的差(0.5到3以及到4),所以我的问题是,如果发现多个最小值,选择结果的规则是什么。

Have a productive day! 祝您有个愉快的一天! :) :)

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. 尝试使用[5,4,3,2,1],您会看到结果为4。

This is consistent with #index which returns the first index position that matches a value. 这与#index一致,该索引返回与值匹配的第一个索引位置。

Think of it as this... 认为这是...

temp_arr = arr.map{ |x| (x-3.5).abs }
arr[temp_arr.index(temp_arr.min)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM