How to “break” out of a case…while in Ruby

2020-07-02 14:07发布

问题:

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?

回答1:

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



回答2:

Here's 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


回答3:

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