O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required