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

thenengah picture thenengah · Jan 5, 2011 · Viewed 50.7k times · Source

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.

Answer

stef picture stef · Jan 5, 2011

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")