我很确定我看到有人做了像下面的代码这样的快捷方式技术(不起作用)
return case guess
when guess > @answer then :high
when guess < @answer then :low
else :correct
end
有人知道我指的是什么技巧吗?
最佳答案
case
语句确实会返回一个值,您只需使用正确的形式来获得您期望的值。
Ruby 中有两种形式的case
。第一个看起来像这样:
case expr
when expr1 then ...
when expr2 then ...
else ...
end
这会将 expr
与使用 ===
的每个 when
表达式进行比较(这是一个三重 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
case
的另一种形式只是一堆 bool 条件:
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
当您认为您使用的是第二种形式时,您使用的是第一种形式,所以您最终会做一些奇怪的(但在语法上有效)的事情,例如:
(guess > @answer) === guess
(guess < @answer) === guess
在任何一种情况下,case
都是一个表达式并返回匹配分支返回的任何内容。
关于ruby - 使 case/switch 返回值的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20671307/