# File.open(filename).each {|line| print line}

**URL:** <https://www.ruby-forum.com/t/file-open-filename-each-line-print-line/209065>\
**Category:** Ruby\
**Created:** [July 5, 2011, 6:34am UTC](https://www.ruby-forum.com/t/file-open-filename-each-line-print-line/209065 "2011-07-05T06:34:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dubstep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/cdc98d/32.png) [@dubstep](https://www.ruby-forum.com/u/dubstep)\
**Post date:** [July 5, 2011, 6:34am UTC](https://www.ruby-forum.com/t/file-open-filename-each-line-print-line/209065/1 "2011-07-05T06:34:34Z")

</div>

I’m thinking about these two codes:

File.open(filename) do |f|  
f.each {|line| print line}  
end

and

File.open(filename).each {|line| print line}

The 1st one, f will be automatically closed. But the 2nd one, I don’t  
know whether a filehandle created by “File.open” will be closed after  
the “each” method has done?

---

<div class="post-metadata">

**Author:** ![joey\_zhou](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joey\_zhou](https://www.ruby-forum.com/u/joey_zhou)\
**Post date:** [July 5, 2011, 8:48am UTC](https://www.ruby-forum.com/t/file-open-filename-each-line-print-line/209065/2 "2011-07-05T08:48:37Z")

</div>

Nope. Another option:

IO.foreach(‘text.txt’) do |line|  
print line  
end

---

<div class="post-metadata">

**Author:** ![joey\_zhou](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joey\_zhou](https://www.ruby-forum.com/u/joey_zhou)\
**Post date:** [July 7, 2011, 8:09am UTC](https://www.ruby-forum.com/t/file-open-filename-each-line-print-line/209065/3 "2011-07-07T08:09:47Z")

</div>

Joey Z. wrote in post #1009075:

> I’m thinking about these two codes:
> 
> File.open(filename) do |f|  
> f.each {|line| print line}  
> end
> 
> and
> 
> File.open(filename).each {|line| print line}
> 
> The 1st one, f will be automatically closed. But the 2nd one, I don’t  
> know whether a filehandle created by “File.open” will be closed after  
> the “each” method has done?

It won’t immediately. However, since you are not storing a reference to  
the File object anyhere, the object will probably be garbage-collected  
at some future point in the program’s execution, and at that point its  
finalizer will be called and the file will be closed.

I say “probably” because ruby’s garbage collector is conservative: if it  
sees a value on the stack that looks like an object reference it will  
treat that object as in use, even if it isn’t.

If you want to experiment, try

ObjectSpace.each\_object(File) { |o| puts o.inspect }
