The return Keyword in Ruby - rubycademy

By Mehdi Farsi

The return Keyword in Ruby

Mehdi Farsi
· 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

produces

before return call
return call

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

produces

Hello Mehdi

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à !

ONE MORE THING ⬇