A case
语句确实返回一个值,您只需使用它的正确形式即可获得您期望的值。
有两种形式case
在红宝石中。第一个看起来像这样:
case expr
when expr1 then ...
when expr2 then ...
else ...
end
这将比较expr
与每个when
表达使用===
(顺便说一句,这是一个三重),它将执行第一个then
where ===
给出一个真实的值。例如:
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
只是一堆布尔条件:
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
是一个表达式并返回匹配分支返回的任何内容。