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

56,859

Solution 1

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

Solution 2

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.

Solution 3

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
Share:
56,859
thenengah
Author by

thenengah

I taught ESL after university, then I started making things for the internet. My favorite tools are mac, ubuntu, vim, tmux, bash, git, javascript/node/express, ruby/rails, react, redux, bootstrap, sass, webpack, gulp, babel, jest, mysql, mongodb, redis, neo4j, rabbitMQ, ELK, nginx, jenkins, AWS.

Updated on November 21, 2020

Comments

  • thenengah
    thenengah over 3 years

    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.