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

explicit return

implicit return

unexpected return s

s return in procs and lambdas

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

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 the return is processed but the return value is completely ignored by our method. Indeed the puts 'hello' is never executed because of the return .

So, 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 ⬇

Feel free to subscribe here: www.rubycademy.com