2010-11-17 92 views
4

我是Ruby的新手,在Ruby的Poignant指南中遇到问题:Ruby中的整数范围

此表达式是否返回true?

2005..2009 === 2007

但我不知道为什么我从下面的代码

wishTraditional.rb:4: warning: integer literal in conditional range 

代码得到这个警告消息:

def makTimeLine(year) 
if 1984 === year 
     "Born." 
elsif 2005..2009 === year 
     "Sias." 
else 
     "Sleeping" 
end 
end 
puts makTimeLine(2007) 

和它返回睡觉,这是错误的,应该是Sias

BTW这两个点是什么意思?我怎样才能找到更多关于它的信息?

回答

11

我想你最好使用类似的东西:

elsif (2005..2009).include?(year) 

这里是文档中关于Ruby ranges

更新:如果你坚持使用===,你应该用括号括起来的范围:

elseif (2005...2009) === year 
+1

感谢Baramin,我刚弄明白我自己,这是覆盖在前面的章节中,我跳过。我不会再跳过章节! – mko 2010-11-17 14:59:17

+0

这是因为运算符的优先级:'==='在'...'之前绑定。 http://stackoverflow.com/a/14258487/1400991 – 2014-12-23 14:43:48

3

对于独立表达式,是的,您需要将范围文字放在括号内。 但是你如果/ ELSIF链会比较像一个case语句,它使用===清洁:

def makTimeLine(year) 
    case year 
    when 1984 
    "Born." 
    when 2005..2009 
    "Sias." 
    else 
    "Sleeping" 
    end 
end