Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "break" out of a case...while in Ruby

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?

like image 553
omninonsense Avatar asked Nov 05 '11 19:11

omninonsense


People also ask

How do you break a case in Ruby?

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.

How do you exit a block in Ruby?

To break out from a ruby block simply use return keyword return if value.

How do you break out of a nested loop in Ruby?

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.


2 Answers

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

like image 62
Gareth Avatar answered Oct 16 '22 09:10

Gareth


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
like image 20
WarHog Avatar answered Oct 16 '22 10:10

WarHog