DEV Community

Kudakwashe Paradzayi
Kudakwashe Paradzayi

Posted on • Originally published at blog.kudapara.co.zw on

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
Enter fullscreen mode Exit fullscreen mode

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

Links

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

Top comments (0)