Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break outer cycle in Ruby?

Tags:

loops

ruby

cycle

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?

like image 886
Fluffy Avatar asked Aug 29 '09 18:08

Fluffy


People also ask

How does nested for loop work in Java?

If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } Here, we are using a for loop inside another for loop.

What is inner loop and outer loop in Java?

A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop.


1 Answers

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 
like image 112
Chris Bunch Avatar answered Sep 28 '22 23:09

Chris Bunch