While using enumerable methods in Ruby, there was a helpful shorthand syntax I came across while practicing coding challenges.
As a beginner, I had first thought the ampersand colon syntax was an operator. I come to find out that the ampersand colon was a hack that first started out in ActiveSupport that become an official feature in Ruby code.
When the “&” is added to the beginning of a method argument, it calls on the to_proc on its operand and passes it in as a block. If you are like me, I had no idea what that meant at first. I had to first learn what to_proc does and what a Proc is.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable. It’ll be easier to show how this works.
Enumerable methods, such as reduce, map and each, accept a block.
You can also call a to_proc method to any object including a symbol. This is what allows Ruby to use the &: syntax.
For each item these methods iterate through, they call the block and pass it as reference to the item. The thing is, the enumerable method “doesn’t know” that this shorthand syntax is going on! The Proc method essentially did most of the work!
This handy method is a neat way to make long lines of code shorter, thus making your code easier to read..(sometimes).