How to break from nested loops in Ruby?

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

    Other posts have referenced an idea similar to creating a "switch" variable. See below for a clear example of how it works. Keep in mind the second loop will still be running until it reaches the end of the employee array, but will not execute any code after the switch is flipped. This is not the optimal way to do this as it can be unnecessarily time expensive if your employee array is large.

    def workforce
      bank.branches do |branch|
        switch = 0
        branch.employees.each do |employee|
          if switch == 1
           next
          end  
          if employee.name = "John Doe"
           switch = 1
          end
       end
     end
    

    After the switch is flipped the inner array will no longer be active and the parent loop will move to the next branch with the switch reset. Obviously more switches can be used for more complex cases.

提交回复
热议问题