Seriously though, What is a Proc in Ruby??

Eric Wahlgren-Sauro
Aug 9, 2017 · 3 min read

I remember a few weeks into my time at Turing School I became curious what a Proc was, but was too busy trying to wrap my head around things like the Ruby Object Model. Well, here I am, a dozen applications later and I still don’t know what a Proc is. Let’s dive in!

A Proc in essence is an anonymous function of block of code that can be represented as an object. This object may be passed around and called at will. We can create a Proc by calling Proc.new, this gives us a Proc object that we can assign to a variable and pass around. When we want the code to execute, we send the variable assigned to the Proc the call method. Here is what this process looks like:

We get back:

We can also substitute the .call(parameter) for [] or a . like so:

We can also generate a Proc without calling .new with the following valid syntax:

So why does any of this matter?

Well a Proc keeps us from having to type out the same blocks over and over. Blocks are one of the few things in Ruby that isn’t considered an object and so consequently you can’t store blocks to be reused. Let’s illustrate this with some example code:

regular block
Proc!

Whoa! This is getting pretty cool. We can imagine how on an application where we have multiple blocks checking against the same list, we might prefer to use Procs to keep us from having to rewrite the same blocks over and over again. I love the idea of a Proc because not only does it keep our code more DRY, but it also is grandparent proof — i.e. it reads well. I love ruby for this reason! Anyways, this is serves as an introduction to what a Proc is. Enjoy!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade