So, I've tried break
, next
and return
. They all give errors, exit
of course works, but that completely exits. So, how would one end a case...when
"too soon?"
Example:
case x
when y; begin
<code here>
< ** terminate somehow ** > if something
<more code>
end
end
(The above is some form of pseudo-code just to give the general idea of what I'm asking [begin...end was used with the hope that break
would work].
And, while I'm at it, is there a more elegant way of passing blocks to case...when
?
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
To break out from a ruby block simply use return keyword return if value.
After the switch is flipped the inner array will no longer be active and the parent loop will move to the next branch with the switch reset. Obviously more switches can be used for more complex cases.
What's wrong with:
case x
when y;
<code here>
if !something
<more code>
end
end
Note that if !something
is the same as unless something
I see a couple of possible solutions. At the first hand, you can define your block of instructions inside some method:
def test_method
<code here>
return if something
<more code>
end
case x
when y
test_method
end
At the other hand, you can use catch-throw
, but I believe it's more uglier and non-ruby way :)
catch :exit do
case x
when y
begin
<code here>
throw :exit if something
<more code>
end
end
end
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