Wrapping Up

In this chapter, we took a deep dive into blocks and how the yield keyword and block_given? method give you the tools you need to write your own methods that leverage blocks.

You learned that, in addition to enumeration, blocks can help with managing resources such as file handles and database connections, and also provide a succinct way to initialize objects.

Blocks, sprinkled with some meta-programming goodness, are also the key to building beautiful DSLs. You’ve learned that instance_eval, with its ability to switch the context of the object based on where it has been invoked, is responsible for many of the DSLs, such as those found in the Rails router and Active Record.

Now that you worked through the examples and exercises, ...

Get Mastering Ruby Closures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.