Chapter 3
The Power of Procs and Lambdas

Recall that blocks by themselves are not objects—they cannot exist by themselves. In order to do anything interesting with a block, you need to pass a block into a method.

Procs have no such restrictions, because they are objects. They allow you to represent a block of code (anything between a do ... end) as an object. Some languages call these anonymous functions, and indeed, they do play the part.

Procs are ubiquitous in real-world Ruby code, although chances are, you might not be using them that much. Through the examples, you’ll learn how to use them effectively in your own code.

Ruby also uses Procs to perform some really nifty tricks. For example, have you ever wondered how ["o","h","a","i"].map(&:upcase) expands to ["o","h","a","i"].map { |c| c.upcase) }? By the end of this chapter, you’ll understand the mechanics of how Ruby performs this sleight of hand.

Procs also assume another form: lambdas. While they serve similar functions (pun intended!), it is also important to learn about their differences, so that you will know when to use which at the right time.

One technique that Procs enable but hasn’t seen very wide use is currying, a functional programming concept. Although its practical uses (with respect to Ruby programming) are pretty limited, it’s still a fun topic to explore.

By the end of this chapter, you should be comfortable enough to use Procs and lambdas in your own code and make them an indispensable part of your Ruby toolbox.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.199.122