Difference between break and return in ruby

What did I learn today 🤔

I learned the difference between break and return keywords in ruby.

Details please

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..200).each do |y|
      puts x*y
      if x*y == target
        break if method == "break"
        return if method == "return"
      end
    end 
  end
end

return exits from the testing function whilst return exits from the (0..200).each loop.

https://stackoverflow.com/questions/4601631/break-and-return-in-ruby-how-do-you-use-them

Comments (3)

j's photo

return exits from the testing function whilst return exits from the (0..200).each loop.

don't you mean break exits the loop?

Sandeep Panda's photo

Cool :-) Why not tag it with TIL (Today I Learned) tag so that it appears here: hashnode.com/feed/til?

Kudakwashe Paradzayi's photo

Software Engineer

Thank you, I did not know about this tag. Fixing it now.