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.
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
while c1
while c2
# execute code
do_break = true if need_to_break_out_of_parent_loop
end
break if do_break
end
My impulse would be to move the nested blocks into a method, with a return
in place of the break
.
def find_branch_and_employee_by_name(bank,emp_name)
bank.branches.each do |branch|
branch.employees.each do |employee|
return([branch,employee]) if employee.name == emp_name
end
end
nil # employee wasn't found
end