Is it good style to explicitly return in Ruby?

前端 未结 8 2059
暗喜
暗喜 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:29

    The style guide states, that you shouldn't be using return on your last statement. You can still use it if it's not the last one. This is one of the conventions which the community follows strictly, and so should you if you plan to collaborate with anyone using Ruby.


    That being said, the main argument for using explicit returns is that it's confusing for people coming from other languages.

    • Firstly, this is not entirely exclusive to Ruby. For example Perl has implicit returns too.
    • Secondly, the majority of the people that this applies to are coming from Algol languages. Most of those are way "lower level" than Ruby, hence you have to write more code to get something done.

    A common heuristic for method length (excluding getters/setters) in java is one screen. In that case, you might not be seeing the method definition and/or have already forgotten about where you were returning from.

    On the other hand, in Ruby it is best to stick to methods less than 10 lines long. Given that, one would wonder why he has to write ~10% more statements, when they are clearly implied.


    Since Ruby doesn't have void methods and everything is that much more concise, you are just adding overhead for none of the benefits if you go with explicit returns.

提交回复
热议问题