From: Peter Hickman Date: 2008-02-15T22:48:52+09:00 Subject: Re: closing files with abrupt interruptions Daniel Brumbaugh Keeney wrote: > loop do > File.open somefile, 'r' do |io| > next > end > end > > Does somefile get closed? > How would I test that? > I have the same question if it raises an error (that gets rescued) or > throws a symbol. > > Daniel Brumbaugh Keeney > > > There are two ways to open a file for reading in ruby, the first is: f = File.open("fred.txt", "r") f.each do |l| puts l end f.close in the above case you have to explicitly close the file, however with this: File.open("fred.txt","r") do |f| f.each do |l| puts l end end The opened file is referenced by the variable f, however f is in the scope of the 'File.open() do ... end' and once the program goes past the closing 'end' the f will be removed. The deletion of the file handle triggers the close. So no need for an explicit close. The second way is also more 'rubyish'.