Is it good style to explicitly return in Ruby?

Viewed 82657

Coming from a Python background, where there is always a "right way to do it" (a "Pythonic" way) when it comes to style, I'm wondering if the same exists for Ruby. I've been using my own style guidelines but I'm thinking about releasing my source code, and I'd like it to adhere to any unwritten rules that might exist.

Is it "The Ruby Way" to explicitly type out return in methods? I've seen it done with and without, but is there a right way to do it? Is there maybe a right time to do it? For example:

def some_func(arg1, arg2, etc)
  # Do some stuff...
  return value # <-- Is the 'return' needed here?
end
8 Answers

No. Good Ruby style would generally only use an explicit returns for an early return. Ruby is big on code minimalism/implicit magic.

That said, if an explicit return would make things clearer, or easier to read, it won't harm anything.

I personally use the return keyword to distinguish between what I call functional methods, i.e. methods that are executed primarily for their return value, and procedural methods that are executed primarily for their side-effects. So, methods in which the return value is important, get an extra return keyword to draw attention to the return value.

I use the same distinction when calling methods: functional methods get parentheses, procedural methods don't.

And last but not least, I also use that distinction with blocks: functional blocks get curly braces, procedural blocks (i.e. blocks that "do" something) get do/end.

However, I try not to be religious about it: with blocks, curly braces and do/end have different precedence, and rather than adding explicit parentheses to disambiguate an expression, I just switch to the other style. The same goes for method calling: if adding parentheses around the parameter list makes the code more readable, I do it, even if the method in question is procedural in nature.

It's a matter of which style you prefer for the most part. You do have to use the keyword return if you want to return from somewhere in the middle of a method.

Like Ben said. The fact that 'the return value of a ruby method is the return value of the last statement in the function body' causes the return keyword to be rarely used in most ruby methods.

def some_func_which_returns_a_list( x, y, z)
  return nil if failed_some_early_check


  # function code 

  @list     # returns the list
end
Related