哈希上的Ruby case语句?

哈希上的Ruby case语句?,ruby,hash,branch,case-statement,Ruby,Hash,Branch,Case Statement,这听起来很奇怪,但我很想这样做: 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 rais

这听起来很奇怪,但我很想这样做:

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 cool_hash[:that_option]”,但我想使用任意数量的选项。另外,我知道Ruby中的case语句只计算第一个true条件块,是否有方法覆盖它来计算每个true块,除非有中断?

您的代码非常接近于有效的Ruby代码。只需删除第一行上的变量名,将其更改为:

case
但是,无法重写case语句来计算多个块。我认为您想要的是使用
if
语句。使用
return
跳出方法,而不是
break

def do_stuff(cool_hash)
  did_stuff = false

  if cool_hash[:target] == "bullseye"
    do_something_awesome
    did_stuff = true
  end

  if cool_hash[:target] == "2 pointer"
    do_something_less_awesome
    return  # for example
  end

  if cool_hash[:crazy_option] == true
    unleash_the_crazy_stuff
    did_stuff = true
  end

  raise "hell" unless did_stuff
end

我认为,下面是做你想做的事情的更好的方法

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部分,如果有更多条件,也可以使用“case cool\u hash[:crazy\u option]”而不是“if”。我希望您在这种情况下使用“if”,因为只有一个条件。

您也可以使用lambda:

case cool_hash
when -> (h) { h[:key] == 'something' }
  puts 'something'
else
  puts 'something else'
end

非常感谢您的快速响应!非常感谢。这很有帮助,希望随着时间的推移,我会用Ruby思考。这正是我想要的!