5

This question is not very useful because the method reference operator was removed from Ruby 2.7.0 before release. This question is left up for historical reasons.

Ruby 2.7.0-preview1 has introduced the method reference operator .: as an experimental feature. (more here and here).

There are some abstract examples available for how to use this new operator:

method = 42.:to_s
 => #<Method: Integer#to_s>
method.receiver
 => 42
method.name
 => :to_s
method.call
 => "42"

and:

method = File.:read
 => #<Method: File.read>
method.call('/Users/foo/.zshrc')
 => "export ZSH=$HOME/.zsh"

These abstract examples are not representative of real-world implementations. What is the plain-English explanation of the purpose and use of the method reference operator, defined in terms of practical and real-world examples?

anothermh
  • 9,815
  • 3
  • 33
  • 52
  • 1
    A description of the method, together with an example of how it can be used to advantage, is given [here](https://dev.to/hanachin/ruby-27-new-feature-method-reference-operator-38l2). That was at the top of the list when I googled "ruby method reference v2.70". For general questions like these, googling is often more effective than asking SO for an explanation. – Cary Swoveland Jun 10 '19 at 02:47
  • “I found that article to be unclear” is a statement, not a question, and SO is all about questions. Also, if you did not find the shortcut for `#method` clearly saving keystrokes in stuff like `[1,42].reject(&42.:==)` self-explaining, I doubt we could be of any help here. – Aleksei Matiushkin Jun 10 '19 at 04:13
  • I looked further into my google results and found nothing helpful other than the article containing the example you provided. You want more and I'm sure other readers, myself included, would like to know more about possible uses of the method, so let's hope you get at least one good answer. – Cary Swoveland Jun 10 '19 at 04:13
  • 1
    @CarySwoveland ruby updates nowadays bring more syntax sugar. `#itself`, safe navigation `&.`, now this. It’s all about saving keystrokes; that simple. Just new alias [with a same not overridable semantics as `__call__`] for `#method`. – Aleksei Matiushkin Jun 10 '19 at 04:14
  • @AlekseiMatiushkin but let's be honest how in love are you with this syntactical sugar. :) – engineersmnky Jun 10 '19 at 14:43
  • @engineersmnky sure I must have been if I still was doing any ruby :) – Aleksei Matiushkin Jun 10 '19 at 14:44

1 Answers1

5

The method reference operator .: is simply syntactic sugar for Object#method just like the function call operator .(). is simply syntactic sugar for #call.

Thus, the use cases for the method reference operator are the exact same ones as the use cases for the Object#method method … just with less keystrokes.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653