Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are return statements bad in Ruby?

Tags:

return

ruby

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.

like image 528
alexloh Avatar asked Jul 14 '11 21:07

alexloh


People also ask

Should I use return in Ruby?

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.

What does return in Ruby do?

Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.

Which functions should not use a return statement?

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.

What happens when a return statement is encountered?

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.


1 Answers

"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.

like image 114
gorootde Avatar answered Oct 06 '22 00:10

gorootde