如何检查ruby中带小数位的范围?
我想在ruby中以9.74 - 9.78之间的数组过滤结果
if (9.74...9.78) == amounts
count += 1
end
这似乎不起作用
答案 0 :(得分:6)
使用Range#cover
执行此操作:
if (9.74...9.78).cover? amounts
count += 1
end
示例:
p (9.74...9.78).cover? 9.75 # => true
p (9.74...9.78).cover? 9.79 # => false
以@m_x建议更新
# will give you the element in the range
array.select{ |item| (9.74..9.78).cover? item }
# will give you the element count in the array belongs to the range
array.count{ |item| (9.74..9.78).cover? item }
答案 1 :(得分:2)
只需将数字括在括号和===
中:
if ((9.74)...(9.78)) === amounts
count += 1
end
编辑:虽然将数字放在括号中似乎没有必要,但无论如何我都建议它清楚说明范围是什么,小数点是什么。