File.open leakage question

If I do:

file = File.open(‘somefile’)

and never close the file, will Ruby automatically close it when the
variable “file” goes out of scope? Or will it stay open until the
program/thread ends?

Ruby will garbage collect the file object assigned to the variable
‘file’ using mark and sweep garbage collection. The file object could
stay in memory after the variable ‘file’ goes out of scope (i.e., no
other object references it) until the next round of garbage collection.
It is possible to automatically close the file object as follows (for
example):

string = File.open(‘somefile’) { |f| f.read } # file is closed
automatically after read is completed

… modify string code …

File.open(‘somefile’, ‘w’) { |f| f.write(string) } # file is closed
automatically after write is completed

Additional code (beyond read and write) can go in the block.

Regards,

Mark

···

On Friday, August 22, 2003, at 09:56 PM, Philip Mak wrote:

If I do:

file = File.open(‘somefile’)

and never close the file, will Ruby automatically close it when the
variable “file” goes out of scope? Or will it stay open until the
program/thread ends?