Equivalent to `break` in ruby ​​case / when statements?

I am looking for an instruction that skips the execution of the when block, similar to break for loops. Is it possible?

What I want to avoid is to build like:

 case n when 1 if valid foo.bar end when 2 if valid foo.foo end 

A more desirable code block would look like this:

 case n when 1 break unless valid foo.bar when 2 break unless valid foo.foo end 

Obviously, break does not work.

+4
source share
2 answers

Equivalent but shorter:

 case n when 1 foo.bar if valid when 2 foo.foo if valid end end 

if the condition really applies to all cases, you can check it in advance:

 if valid case n when 1 foo.bar when 2 foo.foo end end end 

If none of these work for you, then the short answer is: No, there is no break equivalent in the case expression in ruby.

+6
source

I am always a fan of adding conditional expressions to the end of ruby ​​statements. It simplifies and reads the code. This is what the ruby ​​knows. My answer to your question would look something like this:

 case n when 1 foo.bar when 2 bar.foo end unless !valid 
+2
source

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


All Articles