Ruby Quickies #2

to_proc in iterators

yes, I do!

In Ruby code, you quite often see the trick of using an expression like:

as a shorthand form of: { |element| element.to_s }

But, how exactly does it work?

When a parameter is passed with & in front of it (indicating that is it to be used as a block), Ruby will call to_proc on it in an attempt to make it usable as a block.

Symbol#to_proc quite handily returns a Proc that will invoke the method of the corresponding name on whatever is passed to it, thus enabling our little shorthand trick to work.