Reputation: 6882
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
?
Upvotes: 15
Views: 19283
Reputation: 151
Ruby has no built-in way to exit the "when" in a "case" statement. You could however get the desired outcome with an answer similar to the technique WarHog gave:
case x
when y
begin
<code here>
break if something
<more code>
end while false
end
or if you prefer:
case x
when y
1.times do
<code here>
break if something
<more code>
end
end
Upvotes: 4
Reputation: 8710
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
Upvotes: 5
Reputation: 138072
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
Upvotes: 7