How to break from nested loops in Ruby?

crlsrns picture crlsrns · Mar 13, 2011 · Viewed 38k times · Source

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.

Answer

steenslag picture steenslag · Mar 13, 2011

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