File.open and blocks in Ruby 1.8.7
Asked Answered
K

1

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?

Kori answered 26/7, 2011 at 17:12 Comment(0)
A
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.

Ammoniate answered 26/7, 2011 at 17:17 Comment(1)
File.open('somefile.txt', 'r') { |f| f.each_line { |line| puts line } } works as well. Thanks!Kori

© 2022 - 2024 — McMap. All rights reserved.