O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How Symbol#to_proc Works

Symbol#to_proc is one of the finest examples of the flexibility and beauty of Ruby. This syntax sugar allows us to take a statement such as

 words.map { |s| s.length }

and turn it into something more succinct:

 words.map(&​:length​)

Let’s unravel this syntactical sleight of hand by figuring out how this works.

The first step is to figure out the role of the &:symbol. How does Ruby know that it has to call a to_proc method, and why is this only specific to the Symbol class?

When Ruby sees an & and an object—any object—it will try to turn it into a block. This is simply a form of type coercion.

Take to_s, for example. Ruby allows you to do 2.to_s, which returns the string representation of the integer 2

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required