这是一本书中的示例代码。我认为它适用于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
我在Ruby 1.9上运行它,并收到此错误消息:
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"
我该如何更改?
答案 0 :(得分:39)
1.8.x和1.9.x之间的语法发生了变化,现在不再允许:
:
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
技术上:
已替换为then
,但如果您使用换行符,那么这是一个可选关键字。如果您使用旧语法来追踪案例,那将是一件很麻烦的事情,所以希望搜索case
已足够接近。
答案 1 :(得分:11)
根据PickAxe的第3版,它是故意的。
p 125,案例表达:
“Ruby 1.8允许您使用冒号字符代替
then
关键词。这不再受支持。“
示例,使用then
并且没有换行符:
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
答案 2 :(得分:4)
您可以使用半 -colons替换冒号。
刚刚测试了这个例子:
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
我想,在这种情况下,分号与新行完全相同。
答案 3 :(得分:0)
你的投注中有错误
puts generation # not "gemeration"
也尝试这样的事情:
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
答案 4 :(得分:-2)
这是正确的方法:
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