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

后端 未结 4 1711
猫巷女王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:26

    break is called from inside a loop. It will put you right after the innermost loop you are in.

    return is called from within methods. It will return the value you tell it to and put you right after where it was called.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 12:40

    One more example could be if you have two loops in a single method and if you want to come out of the first loop and continue to the second loop use break in the first loop or vice versa:

    def testing(method)
    x=1
      10.times do
        if(x == 2)
         break if method == "break"
        end
       x+=1
      end
      10.times do
       if(x == 5)
         return if method == "return"
       end
      x+=1
      end 
    end
    
    0 讨论(0)
  • 2020-12-23 12:45

    Return exits from the entire function.

    Break exits from the innermost loop.

    Thus, in a function like so:

    def testing(target, method)
      (0..100).each do |x|
        (0..100).each do |y|
         puts x*y
         if x*y == target
           break if method == "break"
           return if method == "return"
         end
        end 
      end
    end
    

    To see the difference, try:

    testing(50, "break")
    testing(50, "return")
    
    0 讨论(0)
提交回复
热议问题