33

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 to solve the problems that can use these constructs.

I can't really post examples because I don't know how to use these so they wouldn't make much sense.

Community
  • 1
  • 1
thenengah
  • 42,557
  • 33
  • 113
  • 157

4 Answers4

87

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")
stef
  • 14,172
  • 2
  • 48
  • 70
  • agreed, this is a really good example! thanks for the clarification – wmock Feb 28 '13 at 18:55
  • 2
    Also keep in mind that using return within a proc that is being called from inside a method will also cause the method to return. Make sure to look up the differences between lambdas and procs. – Jake Hoffner Apr 05 '13 at 03:16
  • 1
    I suggest changing to `(0..10).each` and `testing(5, "break")` for readability. Thanks tho, great answer – Squirrl Sep 11 '14 at 16:19
  • 1
    also there is `next` which moves to the `next` iteration within a loop and also takes a value, just like return and break. – xander-miller Feb 26 '17 at 15:16
8

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.

Null Set
  • 5,374
  • 24
  • 37
2

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
Karol Selak
  • 4,248
  • 6
  • 35
  • 65
0

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
Karol Selak
  • 4,248
  • 6
  • 35
  • 65
srikanth
  • 1
  • 2