使case / switch返回值的快捷方式

时间:2013-12-19 00:25:35

标签: ruby switch-statement

我很确定我看到有人像下面的代码一样执行快捷方式(这不起作用)

return case guess
  when guess > @answer then :high
  when guess < @answer then :low
  else :correct
end

有人知道我所指的诀窍吗?

4 个答案:

答案 0 :(得分:14)

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

另一种形式的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

在任何一种情况下,{{1}}都是一个表达式,并返回匹配的分支返回的内容。

答案 1 :(得分:6)

您需要从guess中移除case,因为它不是有效的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是隐含的。

修改:如果您愿意,可以使用then,相同的示例如下所示:

def test value
  case 
    when value > 3 then :more_than_3
    when value < 0 then :negative
    else :other
  end
end

答案 2 :(得分:4)

这有效:

return case
  when guess > @answer ; :high
  when guess < @answer ; :low
  else ; :correct
  end

答案 3 :(得分:0)

接受@ mu关于这个问题的第一个评论(对我来说看起来很好的方法),你当然也可以写成:

return case (guess <=> @answer)
       when -1 then :low
       when  0 then :correct
       when  1 then :high
       end

       ...
       else
         :high
       end