Ruby 2.7 adds shorthand operator for Object#method

UPDATE

This experimental operator was added in Ruby v2.7.0preview1 but this feature has now been reverted. This won’t be a part of the Ruby v2.7.0 release.

This feature was inspired by functional programming. But according to Matz, instead of this being part of a central design, it was more of an ad hoc addition. He also stated he doesn’t like the Tetris operator .:, which looks like Braille.

Some other community members pointed out that feature requests like this may hinder a systematic expansion of functional programming in Ruby, or at the very least become a useless feature.

The discussion regarding this reversion can be found here along with Matz’s comments.

The examples provided in this post could be tested with Ruby v2.7.0preview1 and v2.7.0preview2.


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

Need help on your Ruby on Rails or React project?

Join Our Newsletter