# Reg IO class

**URL:** <https://www.ruby-forum.com/t/reg-io-class/163613>\
**Category:** Ruby\
**Created:** [March 23, 2009, 7:01am UTC](https://www.ruby-forum.com/t/reg-io-class/163613 "2009-03-23T07:01:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![abirami](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f6c823/32.png) [@abirami](https://www.ruby-forum.com/u/abirami)\
**Post date:** [March 23, 2009, 7:01am UTC](https://www.ruby-forum.com/t/reg-io-class/163613/1 "2009-03-23T07:01:24Z")

</div>

Hi,  
Should we close the file after reading it?

Please see the code below…

data = IO.readlines(“test.txt”,“r”)  
diskfile = File.open(“test.xml”,“w+”)  
data.each do |line|  
line.chomp!  
diskfile.puts(line) if line.length\>0  
end

It is working fine, even without closing the file(diskfile.close). Can  
someone suggest me. Does the file close automatically or not?

Thanks in advance

Abirami

---

<div class="post-metadata">

**Author:** ![abirami](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f6c823/32.png) [@abirami](https://www.ruby-forum.com/u/abirami)\
**Post date:** [March 23, 2009, 7:52am UTC](https://www.ruby-forum.com/t/reg-io-class/163613/2 "2009-03-23T07:52:17Z")

</div>

On 23.03.2009 06:58, Abirami S. wrote:

> Hi,  
> Should we close the file after reading it?

Yes, of course.

> It is working fine, even without closing the file(diskfile.close). Can  
> someone suggest me. Does the file close automatically or not?

In the first line yes, in the second chunk, no. This can be easily  
fixed by using the block form of File.open.

Cheers

robert

---

<div class="post-metadata">

**Author:** ![abirami](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f6c823/32.png) [@abirami](https://www.ruby-forum.com/u/abirami)\
**Post date:** [March 23, 2009, 9:37am UTC](https://www.ruby-forum.com/t/reg-io-class/163613/3 "2009-03-23T09:37:48Z")

</div>

Robert K. wrote:

> On 23.03.2009 06:58, Abirami S. wrote:
> 
> > Hi,  
> > Should we close the file after reading it?
> 
> Yes, of course.
> 
> > It is working fine, even without closing the file(diskfile.close). Can  
> > someone suggest me. Does the file close automatically or not?
> 
> In the first line yes, in the second chunk, no. This can be easily  
> fixed by using the block form of File.open.
> 
> Cheers
> 
> robert

Thank you for your qucik reply
