Ruby hash statement?

This will sound strange, but I would like to do something like this:

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 

Ideally, I would not even need to refer to this again, as this statement is about the case. If I wanted to use only one option, I would have "case cool_hash [: that_option]", but I would like to use any number of options. Also, I know that case statements in Ruby evaluate only the first true conditional block, is there a way to override this to evaluate every block that is true if there is no break?

+6
source share
3 answers

Your code is very close to a valid ruby ​​code. Just remove the variable name in the first line by changing it as follows:

 case 

However, there is no way to override the case statement to evaluate multiple blocks. I think you want to use if . Instead of break you use return to jump out of the method.

 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 
+3
source

You can also use lambda:

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

I think the following is the best way to make the right material.

 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 

Even in the case of the other part, you can use "case cool_hash [: crazy_option]" instead of "if" if there are more conditions. I prefer to use "if" in this case, because there is only one condition.

+4
source

Source: https://habr.com/ru/post/948156/


All Articles