Case expression different in Ruby 1.9?

2020-02-26 17:28发布

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?

标签: ruby
5条回答
贪生不怕死
2楼-- · 2020-02-26 17:32

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.

查看更多
你好瞎i
3楼-- · 2020-02-26 17:32

This is the correct way to do it:

score = 70
result = case score
   when 0..40 then "Fail"
   when 41..60 then "Pass"
   when 61..70 then "Pass with Merit"
   when 71..100 then "Pass with Distinction"
   else "Invalid Score"
end
puts result
查看更多
可以哭但决不认输i
4楼-- · 2020-02-26 17:41

There is a mistake in your puts

puts generation  # not "gemeration"

also try something like this :

score = 70

result = case score
  when 0..40 then "Fail"
  when 41..60 then "Pass"
  when 61..70 then "Pass with Merit"
  when 71..100 then "Pass with Distinction"
  else "Invalid Score"
end

puts result
查看更多
The star\"
5楼-- · 2020-02-26 17:52

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
查看更多
够拽才男人
6楼-- · 2020-02-26 17:55

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.

查看更多
登录 后发表回答