closing files with abrupt interruptions

  • Thread starter Daniel Brumbaugh Keeney
  • Start date
D

Daniel Brumbaugh Keeney

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
 
P

Peter Hickman

Daniel said:
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'.
 
R

Robert Klemme

loop do
File.open somefile, 'r' do |io|
next
end
end

Does somefile get closed?

Yes. See also Peter's explanation.
How would I test that?

Easily:

robert@fussel ~
$ echo 1 > x

irb(main):001:0> io = nil
=> nil
irb(main):002:0> File.open("x") {|io| p io, io.closed?}
#<File:x>
false
=> nil
irb(main):003:0> p io, io.closed?
#<File:x (closed)>
true
=> nil
I have the same question if it raises an error (that gets rescued) or
throws a symbol.

irb(main):004:0> File.open("x") {|io| p io, io.closed?; raise "E"}
#<File:x>
false
RuntimeError: E
from (irb):4
from (irb):4:in `open'
from (irb):4
from :0
irb(main):005:0> p io, io.closed?
#<File:x (closed)>
true
=> nil

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top