ruby是否支持范围语句中的范围?

时间:2010-11-09 03:09:52

标签: ruby

我想这样做:

case cost

    when cost between 1 and 3 then cost * 1.1
    when cost between 3 and 5 then cost * 1.2
else
    0

2 个答案:

答案 0 :(得分:60)

是的,由于Range#===被定义为与include?相同,因此您可以在case语句中使用范围:

case cost
when 1..3 then cost * 1.1
when 3..5 then cost * 1.2

答案 1 :(得分:3)

是。我不知道为什么你没有想到谷歌这个或只是尝试它(这是Ruby的美丽,IMO:事情通常以你认为他们应该的方式工作),但我会回答同样的问题:{{ 3}}

具体做法是:

case expression
when min..max
   statements
else
   statements
end