Block Pattern #2: Managing Resources

Blocks are an excellent way to abstract pre- and post-processing. A wonderful example of that is resource management. Examples of resources that require extra care include file handles, socket connections, and database connections. For example, failure to close a database connection means that down the line, another connection attempt might be refused, since the number of connections that a database can handle is finite and limited.

Remembering to open and close the resource is a largely manual affair. This is error-prone and requires a bit of boilerplate. In the following example, the programmer is trying to open a file and write a few lines to it. The last line is where the programmer closes the file ...

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.