The other day in class, I learned a stylish Ruby shorthand trick called the
Symbol#to_proc, which I now cannot resist using. It allows one to write simple blocks more succinctly.
Assume there’s an array of objects called “frogs”, and you’d like to modify its elements. We’d typically write it like so:
So here, we have a method that takes a block. As this is a frequently occuring pattern of code, Ruby has incorporated a
to_proc method for the
class Symbol, which allows us to do this instead:
You might first wonder what the “&” operator does here. While the & operator usually can couple any object with a block, thus producing a proc, when combined with anything else, the object adhering to the “&” will automatically trigger a “to_proc” hook method, converting––as you may guess––that object to a proc.
Let’s take a peek behind the curtain, as I am curious to know how this happens, and believe that it would be a fun metaprogramming exercise. In the
class Symbol, the method looks a little like this:
Translated to fit our scenario, it’d be:
So, let’s dissect this (pun intended). Within the method, we instantiate a new proc, piping through the object yielded by the block,
.collect––along with any additional arguments. In this example, we just have a
Next, we send
When we call
.send on the frog object, we are actually sending the
:name instance of Symbol, ultimately producing, when all is said and done, this proc:
As a quick summary, during run time, the “&”, detecting that no block is attached to it, triggers the
to_proc hook method for the Symbol class instance, which then generates the above proc, which is then cast to the collect block.
If you were paying close attention, you might have also noticed that what we’ve induced through
to_proc is fundamentally the same as what one would normally write longhand, which brings us back full circle:
Make yourself useful.