Saturday, 5 April 2008

Ruby I/O - Calling with a block does the .close for me

More Ruby niceness. This should look familiar to all Java guys and gals out there:

Repeat after me: "Always be closing. Always be closing. Always be closing."

But Ruby's can also take a block to associate with the call:

This invokes the block, passes the newly opened file to it as a parameter. When this is complete, the file is automatically closed for you.

In addition to this, if an exception ocurs in the first example then the close will never be called until its GC'd. (Bet you'd miss checked exceptions then). With the second example, the file is closed and then the exception is propogated to the caller.

No comments: