How to break from nested loops in Ruby? How to break from nested loops in Ruby? ruby ruby

How to break from nested loops in Ruby?


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 thrownend


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"  endend


while c1 while c2    # execute code    do_break = true if need_to_break_out_of_parent_loop end break if do_breakend