使大小写/开关返回值的快捷方式



我很确定我看到有人做了一个快捷方式技术,就像下面的代码一样(不起作用)

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

这将使用 ===(即三重 BTW)将expr与每个when表达式进行比较,并将执行第一个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 都是表达式,并返回匹配分支返回的任何内容。

您需要从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是隐式的。

编辑:如果您愿意,也可以使用then,相同的示例如下所示:

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

这有效:

return case
  when guess > @answer ; :high
  when guess < @answer ; :low
  else ; :correct
  end
根据@mu对

这个问题的第一条评论(这种方法对我来说看起来不错),你当然也可以把它写成:

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

       ...
       else
         :high
       end

最新更新