The return keyword is optional in ruby so for functions with only one exit point, "return result" can be safely replaced with simply "result".
Is there any Ruby-specific guidelines to when to do this?
I tend to avoid the return keyword as much as possible due to their unruly behavior in procs.
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.
"return" in ruby is only used if you are trying to return more than one value. e.g.
return val1, val2
or if it makes sense to return earlier from a function e.g.
#check if needed param is set
return if !param
#some operations which need param
which is easier than messing your code up with cascaded if-statements.
Conclusion: Use return every time it simplifies your code or it makes it easier to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With