Ruby 2.7 adds shorthand operator for Object#method


Ruby 2.7 adds experimental shorthand operator for Object#method. This allows method object access using :, like File.:basename.

This feature was first proposed 3 years ago and an experimental version of the feature is finally out for use on Ruby 2.7

You can follow more discussion and alternatives to this syntax here.

Before

We can access methods on an Object using the method call on an Object.

object = Object.new
object.methods 
# => [:instance_variable_set, ... :hash ..., :__id__, :__send__]
object.method(:hash)
# => <Method: Object(Kernel)#hash>
# These method objects can be invoked using a call
object.method(:hash).call
# => -1795653931668116237  

We can use this method object returned from object.method, to be passed around, which can then be called elsewhere.

all_ruby_files = Dir["*/*.rb"] 
all_ruby_files.map(&File.method(:basename))

In the example above we are passing method object, returned by File.method(:basename) to the map method.

We are passing a reference to the method here to be called, instead of actually invoking it, by using &.

This is a common pattern, for example:

 # Math.sqrt finds the sqrt of a number
 [1, 4, 9].map(&Math.method(:sqrt))
 # =>  [1.0, 2.0, 3.0]
 

Method shorthand operator

As you can see, calling Object.method(:method_name) can be too verbose. Ruby 2.7 introduces an experimental feature to access methods in a shorthand way.

 # Math.sqrt finds the sqrt of a number
 [1, 4, 9].map(&Math.:(:sqrt))
 # => [1.0, 2.0, 3.0]
 
 # Our first example little simpler
 all_ruby_files = Dir["*/*.rb"] 
 all_ruby_files.map(&File.:basename)
 

Where it can be accessed

The method call is available on Object class. Via Object it is made available on Object instances, Classes, Modules, etc.

Object.new.:hash
Object.:hash
Class.new.:hash
Class.:hash
Module.:hash