4

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?

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Baramin, I just figure it out by myself, this is covered in the previous chapter which I skipped. I wouldn't skip chapter again!
It is because of operator precedence: === binds before .... stackoverflow.com/a/14258487/1400991
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.