I'm looking for a statement that skips the execution of the when
block, similiar to break
for loops. Is this possible?
What I want to avoid is a construct like:
case n
when 1
if valid
foo.bar
end
when 2
if valid
foo.foo
end
The more desirable code block would look like:
case n
when 1
break unless valid
foo.bar
when 2
break unless valid
foo.foo
end
Obviously, break
does not work.
Equivalent but more succinct:
case n
when 1
foo.bar if valid
when 2
foo.foo if valid
end
end
of if the condition really applies to all cases, you can check it beforehand:
if valid
case n
when 1
foo.bar
when 2
foo.foo
end
end
end
If neither works for you, then short answer: No, there's no break
equivalent in a case statement in ruby.
I'm always a fan of adding conditionals to the end of ruby statements. It makes for easier and more readable code. Which is what ruby is known for. My answer to your question would look something like this:
case n
when 1
foo.bar
when 2
bar.foo
end unless !valid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With