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, you have a much better idea how DSLs are implemented, and it shouldn’t feel like magic to you anymore.

Next, we will look at Procs and lambdas—the other forms of closures in Ruby.

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

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