Take the 2-minute tour ×

I'm pretty new to ruby and I'm currently reading the Pickaxe book to get familiar with everything. I came across the File.open section where it discusses taking a block as a parameter to a File.open call then guaranteeing that the file is closed. Now this sounds like an absolutely brilliant way to avoid shooting yourself in the foot and as I'm dangerously low on toes, I figure I'll give it a go. Here is what I wrote (in irb if that matters):

File.open('somefile.txt', 'r').each { |line| puts line }``

My expectation was that the file somefile.txt would get opened, read, printed and closed, right? As far as I can tell wrong. If I use lsof to look at open file handles, it's still open. However, if I do

f = File.open('somefile.txt', 'r').each { |line| puts line }

Am I using blocks wrong in this example or have I failed to understand the meaning of File.open when used with a block. I've read section on ruby-doc.org related to File.open but that just seems to confirm that what I'm doing ought to be working as expected.

Can anyone explain what I'm doing wrong?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

In order to close file after block, you should pass block to File.open() directly, not to each:

File.open('somefile.txt', 'r') do |f| 
  f.each_line { |l| puts l }

File.open(…).each {…} is just iterating over opened file without closing it.

share|improve this answer
File.open('somefile.txt', 'r') { |f| f.each_line { |line| puts line } } works as well. Thanks! –  OldTroll Jul 26 '11 at 17:46

Your Answer


