如何在Ruby中“跳出”一个case语句

15

我已经尝试了breaknextreturn,它们都会报错,当然exit可以工作,但是它会完全退出。那么,如何在case...when中“过早”结束呢?

例如:

case x
    when y; begin
        <code here>
        < ** terminate somehow ** > if something
        <more code>
    end
end

上面是一些伪代码,只是为了让大家大概了解我的问题(使用了begin...end是希望break能够起作用)。

说到这里,是否有更加优雅的方式将块传递给case...when呢?


只需重新构建你的逻辑 - 请参见下文。 - Tilo
只是一条快速提示,你不能在 Ruby 中case中使用break。我尝试过这样做,但会生成语法错误。 - Joshua Pinter
3个回答

7

以下是有问题的内容:

case x
when y;
    <code here>
    if !something
        <more code>
    end
end

请注意,if !somethingunless something 是相同的。这两种写法都与“如果不是某个条件”相同。

绝对什么都没有!我曾经想过,但我一直在寻找正确的方法。我认为除了这种方法之外还有其他正确的方法。所以,如果没有其他方法,我猜这就是正确的方法。谢谢!:D - omninonsense
1
错误在于缩进。如果没有错误,那么语言就不需要breaknext了。 - Nakilon

5

我看到有几种可能的解决方案。

首先,您可以在某个方法中定义指令块:

def test_method
  <code here>
  return if something
  <more code>
end

case x
  when y
    test_method
end

在另一方面,你可以使用catch-throw,但我认为它更加难看且不是 Ruby 的方式 :)
catch :exit do
  case x
    when y
      begin
        <code here>
        throw :exit if something
        <more code>
      end
  end
end

如果我为每种情况都创建一个方法,那看起来会很奇怪,真的很奇怪(而且有很多情况),第二个例子看起来有点...嗯。不过创意加一分。 - omninonsense
但是等等,该return语句仅会从该方法中返回,并不会终止case语句吧? - Michael K Madison

4

Ruby没有内置的方法来退出"case"语句中的"when"。然而,您可以通过类似WarHog提供的技术来获得所需的结果:

case x
when y
    begin
        <code here>
        break if something
        <more code>
    end while false
end

如果你更喜欢的话:
case x
when y
    1.times do
        <code here>
        break if something
        <more code>
    end
end

这将退出内部循环,而不是case-when。尝试在循环后添加puts“this should not be written”并使中断条件为真。 - user9869932
user9869932 - 很好的观点,你是正确的,因为Ruby没有内置的方法来退出“case”语句中的“when”。这个答案是一个建议的方法来获得所需的结果。猜测它假设你想要跳过的代码在循环内部。 - NoonKnight
只循环一次?你一定在开玩笑吧。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接