6

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 }
f.close()

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?

1 Answer 1

8

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 }
end

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

1
  • File.open('somefile.txt', 'r') { |f| f.each_line { |line| puts line } } works as well. Thanks!
    – OldTroll
    Commented Jul 26, 2011 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.