如何打破Ruby的外部循环? [英] How to break outer cycle in Ruby?

查看:80
本文介绍了如何打破Ruby的外部循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,可以像这样打破外部循环:

In Perl, there is an ability to break an outer cycle like this:

AAA: for my $stuff (@otherstuff) {
         for my $foo (@bar) {
             last AAA if (somethingbad());
         }
      }

(语法可能是错误的),它使用循环标签从内部循环内部中断外部循环. Ruby中有类似的东西吗?

(syntax may be wrong), which uses a loop label to break the outer loop from inside the inner loop. Is there anything similar in Ruby?

推荐答案

您想要的是非本地控制流,Ruby提供了以下几种选择:

What you want is non-local control-flow, which Ruby has several options for doing:

  • 继续,
  • 例外,和
  • throw/catch
  • Continuations,
  • Exceptions, and
  • throw/catch

继续

优点:

  • 连续性是非本地控制流的标准机制.实际上,您可以在它们之上构建 any 非本地控制流(子例程,过程,函数,方法,协程,状态机,生成器,条件,异常):它们几乎是GOTO更好的双胞胎.
  • Continuations are the standard mechanism for non-local control-flow. In fact, you can build any non-local control-flow (subroutines, procedures, functions, methods, coroutines, state machines, generators, conditions, exceptions) on top of them: they are pretty much the nicer twin of GOTO.

缺点:

  • 延续不是Ruby语言规范的强制性部分,这意味着某些实现(XRuby,JRuby,Ruby.NET,IronRuby)没有实现它们.因此,您不能依赖它们.

例外

优点:

  • 有一篇论文在数学上证明了异常可以比连续性更强大. IOW:他们可以做延续所能做的所有事情,甚至更多,因此您可以用它们来代替延续.
  • 异常是普遍可用的.

缺点:

  • 它们被称为例外",使人们认为它们仅在特殊情况下".这意味着三件事:读代码的人可能不理解它,实现可能没有针对它进行优化(是的,在几乎所有Ruby实现中,异常 都很慢),最糟糕的是,您他们一看您的代码,就会不知不觉地不休地咕着例外仅在特殊情况下". (当然,他们甚至不会尝试了解您在做什么.)
  • They are called "exceptions" which makes people think that they are "only for exceptional circumstances". This means three things: somebody reading your code might not understand it, the implementation might not be optimized for it (and, yes, exceptions are godawful slow in almost any Ruby implementation) and worst of all, you will get sick of all those people constantly, mindlessly babbling "exceptions are only for exceptional circumstances", as soon as they glance at your code. (Of course, they won't even try to understand what you are doing.)

throw/catch

throw/catch

(大致)如下所示:

catch :aaa do
  stuff.each do |otherstuff|
    foo.each do |bar|
      throw :aaa if somethingbad
    end
  end
end

优点:

  • 与例外相同.
  • 在Ruby 1.9中,对控制流使用异常实际上是语言规范的一部分 !循环,枚举器,迭代器等都使用StopIteration异常终止.
  • The same as exceptions.
  • In Ruby 1.9, using exceptions for control-flow is actually part of the language specification! Loops, enumerators, iterators and such all use a StopIteration exception for termination.

缺点:

  • 与使用异常进行控制流相比,Ruby社区更讨厌它们.

这篇关于如何打破Ruby的外部循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆