In this article, we’re going to explore the following topics:
returnin procs and lambdas
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
before 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.
puts 'after return call' is never executed.
Let’s see what happens if we call
return without value
return keyword returns
nil if no value is passed as argument.
return isn’t explicitly called within a method then Ruby returns the value of the last executed instruction in the method
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
rom_ebook method contains only one instruction the
'Ruby Object Model — eBook' string is returned.
return and assignment methods
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.
MyClass#x= method returns the value passed as argument — in our case
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
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. :-)
ONE MORE THING ⬇
Feel free to subscribe here: www.rubycademy.com
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.