使case / switch返回值的快捷方式
我很确定我看到有人像下面的代码一样执行快捷方式(这不起作用)
return case guess when guess > @answer then :high when guess < @answer then :low else :correct end
有谁知道我指的诀窍?
这有效:
return case when guess > @answer ; :high when guess < @answer ; :low else ; :correct end
case
语句确实返回一个值,你只需要使用它的正确forms来获得你期望的值。
Ruby中有两种forms的case
。 第一个看起来像这样:
case expr when expr1 then ... when expr2 then ... else ... end
这将比较expr
与表达时使用===
(这是一个三重BTW)并且它将执行第一个then
===
给出一个真值。 例如:
case obj when Array then do_array_things_to(obj) when Hash then do_hash_things_to(obj) else raise 'nonsense!' end
是相同的:
if(Array === obj) do_array_things_to(obj) elsif(Hash === obj) do_hash_things_to(obj) else raise 'nonsense!' end
另一种forms的case
只是一堆布尔条件:
case when expr1 then ... when expr2 then ... else ... end
例如:
case when guess > @answer then :high when guess < @answer then :low else :correct end
是相同的:
if(guess > @answer) :high elsif(guess < @answer) :low else :correct end
当你认为你正在使用第二种forms时,你正在使用第一种forms,所以你最终做了一些奇怪的(但语法上有效的)这样的事情:
(guess > @answer) === guess (guess < @answer) === guess
在任何一种情况下, case
都是一个表达式,并返回匹配的分支返回的内容。
你需要从case
删除guess
,因为它不是有效的ruby语法。
例如:
def test value case when value > 3 :more_than_3 when value < 0 :negative else :other end end
然后
test 2 #=> :other test 22 #=> :more_than_3 test -2 #=> :negative
return
是隐含的。
编辑:你可以使用,如果你也喜欢,相同的例子将如下所示:
def test value case when value > 3 then :more_than_3 when value < 0 then :negative else :other end end
接受@ mu关于这个问题的第一个评论(对我来说看起来很好的方法),你当然也可以写成:
return case (guess <=> @answer) when -1 then :low when 0 then :correct when 1 then :high end
要么
... else :high end