Chapter 2
Beautiful Blocks

Blocks are effectively a type of closure. Blocks capture pieces of code that can be passed into methods to be executed later. In a sense, they act like anonymous functions.

Blocks are ubiquitous in Ruby and are one of the defining characteristics of Ruby—you can immediately tell that it’s Ruby code once you see the familiar do ... end or curly braces. It’s virtually impossible to write any meaningful Ruby program without using blocks. In order to understand and appreciate real-world Ruby code, it’s imperative that you understand how blocks work and how to use them.

Rubyists often wax lyrical about blocks—and for good reason. They are a powerful language construct that leads to beautiful and succinct code. They allow you to modify specific behavior without changing the general pieces of your code. This means that you get to do more with less code.

Blocks are also instrumental in crafting domain-specific languages, or DSLs. This ability has been exploited to great effect, especially in tools such as Rake and Rails.

There are two main objectives in this chapter. The first is to make sure you understand how blocks are used. In order to do that, you will learn about the yield keyword and the block_given? method by writing your own methods that take blocks as input. You will also learn what block variables are, and their relationship to blocks acting as closures.

The second objective is to get you well acquainted with the various ways that blocks are used in Ruby—block patterns, if you will. You will write code that enumerates a collection such as an array or a hash. Having the skills to use blocks in conjunction with the classes in the Ruby Standard Library will save you precious time, especially when you start to realize how blocks can make methods extremely versatile.

However, blocks have a lot more to offer than going through the elements of a collection. Other block patterns that are pervasive in real-world Ruby code include resource management, object initialization, and the abstraction of pre- and post-processing. You will be writing code that explores each of these patterns in the sections that follow.

Along the way, you will get to work with some meta-programming goodness and learn the secret to creating Ruby DSLs.

By the end of this chapter, you will gain a deeper appreciation of blocks and understand how to use them effectively in your own code. You will be confident in writing your own code that uses blocks. You will also have an understanding of how DSLs are built in Ruby, and you won’t be intimidated when you look at a foreign-looking DSL.

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

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