Higher-Order Procedures
Throughout this whole chapter, we’ve been taking something for
granted that not all languages can: in Ruby, a Proc is just another object. This means we can
sling these chunks of code around as if they were any other value, which
results in a whole lot of powerful functionality.
This feature is so ingrained in Ruby development, and so well integrated into the system, that it’s easy to overlook. However, I could not in good conscience wrap up a chapter on functional programming techniques without at least showing a simple example of higher-order procedure.
A function is said to be a higher-order function if it accepts another function as input or returns a function as its output. We see a lot of the former in Ruby; basically, we’d see this any time we provide a code block to a method. But functions that return functions might be a bit less familiar to those who are new to the language.
Through closures, we can use a function to essentially build up
customized procedures on the fly. I could show some abstract examples or
academically exciting functionality such as Proc#curry, but instead, I decided that I wanted
to show you something I use fairly frequently.
If you used Rails before Ruby 1.9, you probably were familiar with
the “innovation” of Symbol#to_proc.
What some smart folks realized is that Ruby’s &block mechanism actually calls a hook on
the underlying object, which could be self-defined. Though Symbol#to_proc exists in Ruby 1.9 by default, let’s look at ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access