Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case expression different in Ruby 1.9?

Tags:

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?

like image 765
Anders Lind Avatar asked Feb 16 '12 04:02

Anders Lind


3 Answers

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.

like image 196
tadman Avatar answered Sep 28 '22 02:09

tadman


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 
like image 42
wintersolutions Avatar answered Sep 28 '22 02:09

wintersolutions


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.

like image 37
Owen_AR Avatar answered Sep 28 '22 01:09

Owen_AR