首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >红宝石量化范围

红宝石量化范围
EN

Stack Overflow用户
提问于 2016-05-06 23:33:02
回答 2查看 163关注 0票数 2

我有一个Ruby数组,它定义了一组整数阈值

代码语言:javascript
复制
thresholds = [under_threshold_1, under_threshold_2, ..., under_threshold_n, over_threshold]

我希望将任何整数映射到与阈值数字相对应的值。基本上

代码语言:javascript
复制
if threshold_a <  number < threshold_b
  return threshold_a
end

在Ruby中有这么一种很酷的方法吗?我需要处理“边缘”案件< threshold_1> threshold_over。我只能想出一组(丑陋但有效)的if语句,或者在数组上循环。

实际上,我可以自由地按我想要的方式建模(如果更方便的话,我可以将数组更改为其他东西)。

我在想,也许有一种很酷的方法,可以在一个案例/时间子句中分割阈值。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-07 00:03:32

这个怎么样?

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2016-05-07 00:01:45

我想这就是你想要的:

代码语言:javascript
复制
Thresholds = [4, 8, 10, 12]

def quantify(n)
  Thresholds.count { |t| n >= t }
end

您想要的n的量化恰好是n大于或等于的阈值数,使用Enumerable#count很容易计算它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37082827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档