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
Get Mastering Ruby Closures now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.