Ruby 2.7 new feature: Method reference operator

Seiei Miyagi on January 05, 2019

Method reference operator New operator .: was added. https://bugs.ruby-lang.org/issues/12125 https://github.com/ruby/ruby/commit/67c57... [Read Full]
 
["NG"].any?(&"COPYING".:include?)

I really believe Ruby is moving in the wrong direction. This is not readable.

 

That's my example's problem.

Many other real world use-cases are on the issues.
bugs.ruby-lang.org/issues/12125
bugs.ruby-lang.org/issues/13581

It's handy in block argument for Enumerable methods like map, or select.

 

At first glance this seems a bit voodoo magic compared with the more explicit method, but the more I look at it, the more it does seem to be intuitive compared with other places : is used as a prefix in similar ways in Ruby.

Nice little upcoming addition.

 

: is used as a prefix in similar ways in Ruby.

Eh? : is never used as a prefix in Ruby. :: is—for namespacing in FQ names—but this is probably not as similar.

: as a prefix is used in Ruby only to declare symbols. If you think about [42].map(&:to_s) notation, there is no syntactic sugar. :to_s there is an old good plain symbol. It works because Symbol#to_proc is defined, no magic involved. & in arguments list calls to_proc on the argument and passes the result as a block to the calling method, e.g. symbol converted to a proc is passed to the receiver as a block parameter.

The naïve implementation of Symbol#to_proc in Ruby might be similar to the working implementation of the same for the string:

class String
  def to_proc
    ->(recv) { recv.send self }
  end
end

[42].map(&"to_s")
#⇒ ["42"]
 

I don't like this syntax, at all.

It shaves off a few characters, but massively damages readability.

How is a new developer to make sense of this syntax? One thing ruby is really good at is "reading like English"; but this syntax appears more optimised for code golf than for human understanding.

 

In other programming languages, they have more convenient way to reference the method.

gist.github.com/americodls/20981b2...
bugs.ruby-lang.org/issues/13581

IMO, the difference between Ruby and other languages is method calling.
Other languages can reference the method by .method_name without (), but ruby can't because Ruby doesn't need () for method call.

The .: looks like method calling ., with additional : can reference the method. That makes sense to me.

 

With this syntactic sugar 'self.:puts.call("Enjoy!")' looks quite inconsistent :) Should be probably:

'self.:puts.("Enjoy!")'
 

Updated the code, Thanks for improvements!

code of conduct - report abuse