How to break from nested loops in Ruby?

前端 未结 6 708
感情败类
感情败类 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:43

    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
    

提交回复
热议问题