11

奇妙に聞こえるかもしれませんが、私は次のようなことをしたいと思っています。

case cool_hash
  when cool_hash[:target] == "bullseye" then do_something_awesome
  when cool_hash[:target] == "2 pointer" then do_something_less_awesome
  when cool_hash[:crazy_option] == true then unleash_the_crazy_stuff
  else raise "Hell"
end

理想的には、has を再度参照する必要さえありません。これは case ステートメントに関するものだからです。オプションを 1 つだけ使用したい場合は、「case cool_hash[:that_option]」としますが、任意の数のオプションを使用したいと考えています。また、Ruby の case ステートメントは最初の true 条件付きブロックのみを評価することを知っています。これをオーバーライドして、ブレークがない限り true であるすべてのブロックを評価する方法はありますか?

4

3 に答える 3

21

ラムダを使用することもできます:

case cool_hash
when -> (h) { h[:key] == 'something' }
  puts 'something'
else
  puts 'something else'
end
于 2015-03-26T19:11:27.803 に答える
4

以下は、あなたが望むことを行うためのより良い方法だと思います。

def do_awesome_stuff(cool_hash)
  case cool_hash[:target]
    when "bullseye"
      do_something_awesome
    when "2 pointer"
      do_something_less_awesome
    else
     if cool_hash[:crazy_option]
      unleash_the_crazy_stuff
     else
      raise "Hell"
     end
  end
end

case の else 部分でも、さらに条件がある場合は、'if' の代わりに 'case cool_hash[:crazy_option]' を使用できます。条件が 1 つしかないため、この場合は「if」を使用することをお勧めします。

于 2013-06-27T05:40:18.953 に答える