我有一个Ruby数组,它定义了一组整数阈值
thresholds = [under_threshold_1, under_threshold_2, ..., under_threshold_n, over_threshold]我希望将任何整数映射到与阈值数字相对应的值。基本上
if threshold_a < number < threshold_b
return threshold_a
end在Ruby中有这么一种很酷的方法吗?我需要处理“边缘”案件< threshold_1和> threshold_over。我只能想出一组(丑陋但有效)的if语句,或者在数组上循环。
实际上,我可以自由地按我想要的方式建模(如果更方便的话,我可以将数组更改为其他东西)。
我在想,也许有一种很酷的方法,可以在一个案例/时间子句中分割阈值。
case number
when 0..threshold_1 then 0
when threshold_i..threshold_i+1 then i
else n
end
# example
thresholds = [ 4, 8, 10 ,12 ]
quantify(1) = 0
quantify(4) = 1
quantify(11) = 3
quantify(50) = 4发布于 2016-05-07 00:03:32
这个怎么样?
thresholds = [ 4, 8, 10, 12 ]
def which_threshold(thresholds, n)
thresholds.find_index {|t| n < t } || thresholds.size
end
p which_threshold(thresholds, 1) # => 0
p which_threshold(thresholds, 4) # => 1
p which_threshold(thresholds, 11) # => 3
p which_threshold(thresholds, 50) # => 4发布于 2016-05-07 00:01:45
我想这就是你想要的:
Thresholds = [4, 8, 10, 12]
def quantify(n)
Thresholds.count { |t| n >= t }
end您想要的n的量化恰好是n大于或等于的阈值数,使用Enumerable#count很容易计算它。
https://stackoverflow.com/questions/37082827
复制相似问题