views:

436

answers:

4

Coming from a Python background, where there is always a "right way to do it" (a "Pythonic" way, if you will) when it comes to style, I'm wondering if the same exists for Ruby. I've kind of 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.

So my question is: 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)
  value = arg1 + arg2 + etc #or whatever
  # Do some stuff...
  return value # <-- Is the 'return' needed here?
end
+15  A: 

no, good ruby style generally only uses explicit returns for an early return. Ruby is big on code minimalism/implicit magic. That said, if an explicit return would make things much clearer or easier to read, it won't harm anything.

Ben Hughes
A: 

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)
  if failed_some_early_check
    return nil

  # function code 

  @list     # returns the list
end
Gishu
you could also write "return nil if failed_some_early_check" if your intention is still clear
Mike Woodhouse
A: 

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.

Praveen Angyan
+4  A: 

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.

Jörg W Mittag
Right now I omit a return in any "one-liners", which is similar to what you're doing, and I do everything else the same. Good to know I'm not completely off in my style. :)
musicfreak