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

放肆的年华 提交于 2019-12-09 14:36:43

问题


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:


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



回答3:


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


来源:https://stackoverflow.com/questions/8022865/how-to-break-out-of-a-case-while-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!