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

查看:17
本文介绍了如何打破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 是非本地控制流的标准机制.事实上,您可以在它们之上构建任何非本地控制流(子例程、过程、函数、方法、协程、状态机、生成器、条件、异常):它们几乎是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

这是(大致)它的样子:

This is (roughly) what it would look like:

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天全站免登陆