Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the method reference operator .: work?

Tags:

ruby

ruby-2.7

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?

like image 540
anothermh Avatar asked Jun 10 '19 01:06

anothermh


People also ask

What is an method reference?

Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Instance methods of an arbitrary object of a particular type

What is method reference in Java 8?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression.

What is method reference in lambda expression?

Method references are a special type of lambda expressions. They’re often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects. Instance methods of an arbitrary object of a particular type. Constructor.

How to point to methods by their names?

Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −. Static methods. Instance methods. Constructors using new operator (TreeSet::new)


1 Answers

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.

like image 98
Jörg W Mittag Avatar answered Oct 06 '22 01:10

Jörg W Mittag