# File.open leakage question

**URL:** <https://rubytalk.org/t/file-open-leakage-question/7583>\
**Category:** ruby-talk\
**Created:** [23 August 2003 01:56 UTC](https://rubytalk.org/t/file-open-leakage-question/7583 "2003-08-23T01:56:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Philip\_Mak1](https://avatars.discourse-cdn.com/v4/letter/p/3ab097/32.png) [@Philip\_Mak1](https://rubytalk.org/u/Philip_Mak1)\
**Post date:** [23 August 2003 01:56 UTC](https://rubytalk.org/t/file-open-leakage-question/7583/1 "2003-08-23T01:56:50Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Mark\_Wilson](https://avatars.discourse-cdn.com/v4/letter/m/a3d4f5/32.png) [@Mark\_Wilson](https://rubytalk.org/u/Mark_Wilson)\
**Post date:** [23 August 2003 02:09 UTC](https://rubytalk.org/t/file-open-leakage-question/7583/2 "2003-08-23T02:09:47Z")

</div>

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?
