Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break from nested loops in Ruby?

assume the following ruby code:

bank.branches do |branch|   branch.employees.each do |employee|     NEXT BRANCH if employee.name = "John Doe"   end end 

NEXT BRANCH is of course pseudocode. is there a way that i can break out of a parent loop, the way one can do so in Perl, for example (by employing loop labels)?

thanks in advance.

like image 439
crlsrns Avatar asked Mar 13 '11 01:03

crlsrns


People also ask

How do you break out of nested?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break out of a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

What does break return in Ruby?

break is called from inside a loop. It will put you right after the innermost loop you are in. return is called from within methods. It will return the value you tell it to and put you right after where it was called.

How do you stop an infinite loop in Ruby?

This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.


2 Answers

Catch and throw might be what you are looking for:

bank.branches do |branch|   catch :missingyear do  #:missingyear acts as a label     branch.employees.each do |employee|       (2000..2011).each do |year|         throw :missingyear unless something  #break out of two loops       end     end   end #You end up here if :missingyear is thrown end 
like image 190
steenslag Avatar answered Sep 30 '22 05:09

steenslag


There's no built-in way to break out of containing blocks without their consent. You'll just have to do something like:

bank.branches do |branch|   break unless branch.employees.each do |employee|     break if employee.name == "John Doe"   end end 
like image 39
Chuck Avatar answered Sep 30 '22 05:09

Chuck