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

て烟熏妆下的殇ゞ 提交于 2019-12-04 00:13:41

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
NoonKnight

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