How to break from nested loops in Ruby?

前端 未结 6 688
感情败类
感情败类 2020-12-15 15:00

assume the following ruby code:

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


        
6条回答
  •  时光取名叫无心
    2020-12-15 15:23

    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
    

提交回复
热议问题