The return Keyword in Ruby

Mehdi Farsi
Sep 18, 2018 · 2 min read

In this article, we’re going to explore the following topics:

  • explicit return
  • implicit return
  • unexpected returns
  • return in procs and lambdas

Explicit return

Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.

This keyword is named as return


Here, we can see that a call to explicit_return_call executes all the instructions until the call to return 'return call'.

When this instruction is executed the execution flow is suddenly stopped and the 'return call' string is returned.

So, the puts 'after return call' is never executed.

Let’s see what happens if we call return without value

The return keyword returns nil if no value is passed as argument.

Implicit return

when return isn’t explicitly called within a method then Ruby returns the value of the last executed instruction in the method

In the implicit_return method, as if true is always evaluated as true (mister obvious) then the last executed instruction is 42. So the method logically returns 42.

As the rom_ebook method contains only one instruction the 'Ruby Object Model — eBook' string is returned.

return and assignment methods

The return keyword behaves differently when it has to deal with assignment methods

Here we can see that our return statement is completely omitted by our method.

Instead, the MyClass#x= method returns the value passed as argument — in our case 21.

unexpected returns

The return keyword can only be used within a method


Here we see that a call to return outside of a method – even within a block raises a LocalJumpError.

Otherwise, calling return in a block that is encapsulated in a method is a valid syntax.

Return In procs and lambdas

The return keyword, when it’s called in proc or lambda, behaves differently.

I’ve already covered these differences in the Proc vs Lambda article.

Feel free to read it to for further information. :-)

Voilà !


Feel free to subscribe here:

Feel free to 👏 and share this article if it has been useful for you. 🚀

Here is a link to my last article: alias in Ruby.


E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of — Ruby & Ruby on Rails - Paris


E-Learning platform for Ruby and Ruby on Rails

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade