关于散列的Ruby Case语句?

rkttyhzu  于 2022-10-15  发布在  Ruby
关注(0)|答案(4)|浏览(142)

这听起来可能有些奇怪,但我很乐意做这样的事情:

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块,除非有中断?

yfwxisqw

yfwxisqw1#

您还可以使用lambda:

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

6mzjoqzu2#

您的代码非常接近有效的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
kb5ga3dv

kb5ga3dv3#

我认为,遵循是做你想做的事情的更好的方式。

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_Hash[:CrawOption]’而不是‘If’。我更喜欢在这种情况下使用‘if’,因为只有一个条件。

7fhtutme

7fhtutme4#

Ruby 3.0中,您可以使用pattern matching执行以下操作


# assuming you have these methods, ruby 3 syntax

def do_something_awesome = "something awesome 😎"
def do_something_less_awesome = "something LESS awesome"
def unleash_the_crazy_stuff = "UNLEASH the crazy stuff 🤪"

你可以做到的

def do_the_thing(cool_hash)
  case cool_hash
  in target: "bullseye" then do_something_awesome
  in target: "2 pointer" then do_something_less_awesome
  in crazy_option: true then unleash_the_crazy_stuff
  else raise "Hell"
  end
end

会回来的

do_the_thing(target: "bullseye")
=> "something awesome 😎"

do_the_thing(target: "2 pointer")
=> "something LESS awesome"

do_the_thing(crazy_option: true)
=> "UNLEASH the crazy stuff 🤪"

Ruby 2.7中,它仍然有效


# need to define the methods differently

def do_something_awesome; "something awesome 😎"; end
def do_something_less_awesome; "something LESS awesome"; end
def unleash_the_crazy_stuff; "UNLEASH the crazy stuff 🤪"; end

# and when calling the code above to do the switch statement

# you will get the following warning

warning: Pattern matching is experimental, and the behavior may change
         in future versions of Ruby!

相关问题