Is it good style to explicitly return in Ruby?

前端 未结 8 2052
暗喜
暗喜 2020-11-27 10:59

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\'v

相关标签:
8条回答
  • 2020-11-27 11:44

    Actually the important thing is to distinguish between:

    1. Functions - methods executed for their return value
    2. Procedures - methods executed for their side effects

    Ruby does not have a native way of distinguishing these - which leaves you vulnerable to writing a procedure side_effect() and another developer deciding to abuse the implicit return value of your procedure (basically treating it as an impure function).

    To resolve this, take a leaf out of Scala and Haskell's book and have your procedures explicitly return nil (aka Unit or () in other languages).

    If you follow this, then using explicit return syntax or not just becomes a matter of personal style.

    To further distinguish between functions and procedures:

    1. Copy Jörg W Mittag's nice idea of writing functional blocks with curly braces, and procedural blocks with do/end
    2. When you invoke procedures, use (), whereas when you invoke functions, don't

    Note that Jörg W Mittag actually advocated the other way around - avoiding ()s for procedures - but that's not advisable because you want side effecting method invocations to be clearly distinguishable from variables, particularly when arity is 0. See the Scala style guide on method invocation for details.

    0 讨论(0)
  • 2020-11-27 11:44

    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
    
    0 讨论(0)
提交回复
热议问题