On 02.01.2008 13:30, Esmail wrote:
> Robert Klemme wrote:
>> On 02.01.2008 05:40, Esmail wrote:
>>> MonkeeSage wrote:
>>>>
>>>> Ps. ruby will normally close open file handles on garbage collection
>>>> or in finalization, but just in case of some catastrophic failure
>>>> (what, I'm not sure), it's usually considered good practice to close
>>>> file handles manually:
>>>>
>>>> ...
>>>>      file=File.open(ARGV[0])
>>>>      data=file.readlines
>>>>      file.close
>>>
>>> Ooops, absolutely, that sort of houskeeping needs to be done, I'm good
>>> doing with C and Java .. not sure why I didn't think about this with 
>>> Ruby.
>>>
>>> By the way, I know if I do something like
>>>
>>> File.open("bla").each { |line|
>>>   stuff
>>> }
>>>
>>> the file gets automagically closed at the end of the block.
>>
>> I'm sorry, but this is wrong.  
> 
> I have used this code snippet in the past without problems in
> several scripts.
> 
> This is where I got it originally from:
> 
> http://pleac.sourceforge.net/pleac_ruby/fileaccess.html

Note that this page does not claim automated closing of the IO object 
for this code snippet as far as I can see.  It just uses this to 
demonstrate that you can use #each with an IO object.

After looking at this I suggest you rather use the Pickaxe as your 
reference - even the first version (which is online) is better than what 
this page suggests.  There are various issues with the code on the page 
that you referred, e.g. not closing IO objects under all circumstances, 
especially the example with "bla.txt" is overly complex.

http://ruby-doc.org/docs/ProgrammingRuby/

IO is here:
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_io.html

> Are you saying I am wrong about the file being closed at the
> end of the block,

Exactly.

> or the whole construct?

Well, the former kind of obsoletes the whole construct, doesn't it? ;-)

> You either need to do
>>
>> File.open("bla") do |io|
>>   io.each do |line|
>>     # stuff
>>   end
>> end
>>
>> or
>>
>> File.foreach "bla" do |line|
>>   # stuff
>> end
>>
>>> What about the example you gave, data=IO.read("bla") ... I assume the
>>> file gets opened, read and closed in one fell swoop, correct?
>>
>> This is correct.
> 
> Cool .. thanks for confirming this.

You're welcome.

Kind regards

	robert