Written January 8, 2015. Tagged Ruby.
Ruby 2.1 changed method definitions from returning
nil to returning the method name:
def foo; end # => :foo
def self.foo; end # => :foo
This enables shorter and DRYer code like
private_class_method def self.foo
I've mostly used it for Rails'
helper_method and once or twice for
I use a special syntax, though, that I would like to present for your consideration:
The trailing backslash is just the (rarely used) Ruby syntax to say "this expression continues on the next line". You can think of it as escaping the line break so it has no effect (as a mnemonic – it's not what actually happens).
I know, it looks weird. But if you try it, I think you'll come to like it.
I see these benefits compared to the pre-2.1 style:
(If you want to memoize with this very syntax, see memoit by Jonas Nicklas.)
I see these benefits compared to the
helper_method def foo oneliner style:
def …at the beginning of the line so the code is easier to scan.
It has one single downside that I can think of:
I would argue that this is minor. Any initial headscratching is a one-time cost per developer. If they know Ruby well enough to understand the oneliner, they can make sense of this as well.
If not, feel free to send them to this post.