rubyloopscycle

How to break outer cycle in Ruby?


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());
         }
      }

(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?


Solution

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

    Continuations

    Pros:

    Cons:

    Exceptions

    Pros:

    Cons:

    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
    

    Pros:

    Cons: