开发者

Integer Range in Ruby

I'm a newbie to Ruby, I have a problem following the Poignant Guide to Ruby:

Does this expression return true?

2005..2009 === 2007

But I don't know why I got this warning message from the开发者_运维知识库 following code

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

code:

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

and the it return Sleeping, which is wrong and should be the Sias

BTW what does the two dots mean? How can I find more information about it?


I think you better use something like that :

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

Here is the documentation about Ruby ranges

Update: if you insist on using ===, you should enclose the range in parentheses:

elseif (2005..2009) === year


For independent expressions, yes, you'll need to put range literals in parentheses. But your if/elsif chain would be cleaner as a case statement, which uses === for comparison:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜