Project Ramon

A learning journey from a Ruby noob perspective

Procs & Lambdas pt.1

lambda surprise!

Today I learned a bit about when and how to use Procs and Lambdas.

At first read of the documentation I found it a bit notional (probably due to my lack of understanding about how they worked), but quickly changed my tune after completing the codeacadmy lesson, and watching this Ruby Tapas video by @avdi. In no time, I was enjoying small eureka moments while working the exercises out on my own. Hence the title photo!

I learned that not ‘everything’ in Ruby is an object. For instance a Ruby code block is not an object. You can however, bind a code block to a Proc object, assign it to a variable, and then call the variables that house the Proc object.

Here are a couple of ways I found to create a Proc object. The first instantiates a proc object wrapped in a method. The second way demonstrates a code block bound to a Proc object, that’s assigned to a variable.

When you are ready to call the code, you can simply use the ‘call’ method like so:

In Ruby, there are methods that accept blocks, and there are those that don’t. Fortunately there is a way to allow our user defined methods to accept a block of code with the ‘yield’ keyword. Check it out:

One of the useful methods I learned go well with code blocks is ‘collect’. The ‘collect’ method applies the code in the block to each element in an array.

Here’s a quick example:

You can also pass parameters to the yield call like so:

So when would you or I recognize an opportunity to use a Proc? Whenever we have blocks and want reuse them instead of re-typing. We can store a block for later use by using the Proc object. We can store a Proc in a variable, and then explicitly pass it to any method that accepts a callable object.

Advertisements

Categories: AirPair, Newbie, Ruby, Ruby on rails

Tags: , , , ,

1 reply

Trackbacks

  1. Procs & Lambdas pt.2 | Project Ramon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s