The return Keyword in Ruby
source link: https://www.tuicool.com/articles/hit/JVrAVrJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The return Keyword in Ruby
In this article, we’re going to explore the following topics:
return return return return return
Feel free to have a look to my new eBook : :book: RUBY OBJECT MODEL :book::gem:
Explicit return
Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value
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'
. Then the call to return
stops the execution flow.
So the puts 'after return call'
is never executed.
Let’s see what happens if we call return
without passing it a 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 x=
method returns the value passed as argument — in our case 3
.
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à !
Thank you for taking the time to read this post :-)
:gem::gem:Here’s a link to my new ebook project :book: Ruby Object Model :book: !! :gem::gem:
Feel free to :clap: and share this article if it has been useful for you. :rocket:
Here is a link to my last article: alias in Ruby
.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK