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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With