break and return in ruby, how do you use them?

后端 未结 4 1742
猫巷女王i
猫巷女王i 2020-12-23 11:52

I just asked a question about return and it seems to do the same thing as break. How do you use return, and how do you use break, such as in the actual code that you write t

4条回答
  •  一个人的身影
    2020-12-23 12:39

    I wanted to edit the approved answer to simplify the example, but my edit was rejected with suggestion of making new answer. So this is my simplified version:

    def testing(target, method)
      (1..3).each do |x|
        (1..3).each do |y|
         print x*y
         if x*y == target
           break if method == "break"
           return if method == "return"
         end
        end 
      end
    end
    

    we can see the difference trying:

    testing(3, "break")
    testing(3, "return")
    

    Results of first (break statement exiting innermost loop only when 3 reached):

    1232463
    

    Results of last (return statement exiting whole function):

    123
    

提交回复
热议问题