Chapter 10. Blocks, Procs, and Lambdas

image with no caption

When programmers talk about blocks, they often mean some arbitrary “chunks” of code. In Ruby, however, a block is special. It is a unit of code that works somewhat like a method but, unlike a method, it has no name.

Blocks are very important in Ruby, but they can be difficult to understand. In addition, there are some important differences in the behavior of blocks in Ruby 1.8 and Ruby 1.9. If you fail to appreciate those differences, your programs may behave in unexpected ways when run in different versions of Ruby. This chapter looks at blocks in great detail. Not only does it explain how they work and why they are special, but it also provides guidance on ensuring that they continue to work consistently no matter which version of Ruby you happen to be using.

What Is a Block?

Consider this code:

1blocks.rb

3.times do |i|
    puts( i )
end

It’s probably pretty obvious that this code is intended to execute three times. What may be less obvious is the value that i will have on each successive turn through the loop. In fact, the values of i in this case will be 0, 1, and 2. The following is an alternative form of the previous code. This time, the block is delimited by curly brackets rather than by do and end.

3.times { |i|
    puts( i )
}

According to the Ruby documentation, times is a method of Integer (let’s call the Integer int), which iterates a block “int times, passing in values from 0 to int −1.” So here, the code within the block is run three times. The first time it is run, the variable i is given the value 0; each subsequent time, i is incremented by 1 until the final value, 2 (that is, int−1), is reached.

The two code examples shown earlier are functionally identical. A block can be enclosed either by curly brackets or by the do and end keywords, and the programmer can use either syntax according to personal preference.

Note

Some Ruby programmers like to delimit blocks with curly brackets when the entire code of the block fits onto a single line and with do..end when the block spans multiple lines. My personal prejudice is to be consistent, irrespective of code layout, so I generally use curly brackets when delimiting blocks. Usually your choice of delimiters makes no difference to the behavior of the code—but see Precedence Rules in Precedence Rules.

If you are familiar with a C-like language such as C# or Java, you may, perhaps, assume that Ruby’s curly brackets can be used, as in those languages, simply to group together arbitrary “blocks” of code—for example, a block of code to be executed when a condition evaluates to true. This is not the case. In Ruby, a block is a special construct that can be used only in very specific circumstances.

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

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