What the Proc is a Proc?

August 27, 2014

Today I was reading some C# code that passed around delegates. Delegates are analogous to function pointers. Thus, delegates allow you to pass around methods. So how does one accomplish this in Ruby? Well, pretty simple, you use a Proc object.

Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables. Procs encapsulate behavior, so you can use a Proc as a callback. A callback is invoked when a particular event happens, and the callback function will be called, and this notifies your code that something of interest has taken place. This can be very useful in logging or in an eventing system where you want some logic to be triggered once something happens

Let’s say for instance we want ‘Awesome’ to be printed whenever something cool happens in our database code. First thing we would do is create a method that will print out ‘Awesome’ like so

Next we will write the code that is going to use this method, we also invoke the Proc by using the call method.

Doing this you will see ‘Awesome’ printed to your screen, fairly boring but we can make it more exciting.

Next let’s create a method that will take in the Proc and execute it. We are going to use the ‘&block’ syntax to pass in our Proc, using a ‘&block’ will also allow us to pass in a block of code and run it.

Here is my quick explanation of what is the difference between a Proc and a block. A Proc is an object whereas a block is an anonymous function.

Here is our method:

Now we can call our method passing in our Proc.

some_call(&proc)

Calling our method passing in our earlier defined Proc object will result in ‘Awesome’ being printed to the screen. We can also call the ‘some_call’ method with a block.

some_call do 
    puts 'Juice'
end

This will result in ‘Juice’ printed to the screen.

The Proc object is pretty powerful, it is pretty straightforward to use, and there are numerous uses for it. Just think of Proc as a function pointer or as a delegate, and you will have a good idea how it works.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus