This is an example code from a book. I assume it's for Ruby 1.8.
birthyear = 1986
generation = case birthyear
when 1946...1963: "Baby boomer"
when 1964...1976: "Generation X"
when 1977...2012: "new generation"
else nil
end
puts generation
I ran it on Ruby 1.9, and got this error message:
Untitled 2.rb:12: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n'
when 1946...1963: "Baby boomer"
^
Untitled 2.rb:13: syntax error, unexpected keyword_when, expecting $end
when 1964...1976: "Generation X"
How should I change this?
You can just replace the colons with semi-colons.
Just tested this example:
The semi-colon works exactly the same as a new line in this context, I think.
This is the correct way to do it:
There is a mistake in your puts
also try something like this :
According to the 3rd edition of the PickAxe, it is intentional.
p 125, Case Expressions :
example, with
then
and no newlines:There was a change in the syntax between 1.8.x and 1.9.x where the
:
is now no longer allowed:Technically
:
has been replaced bythen
but that's an optional keyword if you use a newline. It's a bit of a hassle to go and track down cases where you've used the old syntax, so hopefully searching forcase
is close enough.