Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.open and blocks in Ruby 1.8.7

Tags:

file-io

ruby

irb

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?

like image 849
OldTroll Avatar asked Jul 26 '11 17:07

OldTroll


1 Answers

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.

like image 176
Victor Deryagin Avatar answered Sep 18 '22 04:09

Victor Deryagin