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?
There was a change in the syntax between 1.8.x and 1.9.x where the :
is now no longer allowed:
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
Technically :
has been replaced by then
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 for case
is close enough.
According to the 3rd edition of the PickAxe, it is intentional.
p 125, Case Expressions :
"Ruby 1.8 allowed you to use a colon character in place of the
then
keyword. This is no longer supported."
example, with then
and no newlines:
birthyear = 1986 generation = case birthyear when 1946...1963 then "Baby boomer" when 1964...1976 then "Generation X" when 1977...2012 then "new generation" else nil end puts generation
You can just replace the colons with semi-colons.
Just tested this example:
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
The semi-colon works exactly the same as a new line in this context, I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With