How to break outer cycle in Ruby?

Fluffy picture Fluffy · Aug 29, 2009 · Viewed 27k times · Source

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?

Answer

Chris Bunch picture Chris Bunch · Aug 29, 2009

Consider throw/catch. Normally the outside loop in the below code will run five times, but with throw you can change it to whatever you like, breaking it in the process. Consider this perfectly valid ruby code:

catch (:done) do
  5.times { |i|
    5.times { |j|
      puts "#{i} #{j}"
      throw :done if i + j > 5
    }
  }
end