Proc, Ampersand, & shorter Ruby Code

While using enumerable methods in Ruby, there was a helpful shorthand syntax I came across while practicing coding challenges.

Image for post
Image for post

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.

Image for post
Image for post

Enumerable methods, such as reduce, map and each, accept a block.

Image for post
The reduce method using the Ampersand syntax

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).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store