Is this safe? When will the file be closed? For IO it's said:
"I/O streams are automatically closed when they are claimed by
the garbage collector." Is this true for files as well, (File
is a subclass of IO)?
I know you can do...
File.open("file.ext", "w"){|f| f.write data}
...., but the first one is shorter and better readable.
The file handle will indeed stay open until the File instance is GC'd.
The block-passing version is a few extra characters, but is much
better for long-running processes, or those which open large numbers
of files, as it automatically closes the file at the end of the block.
I don't think it can be collected during the #write method, because the File object is the value of "self" during the method. It's reachable, so it shouldn't be collected.
Still, there are good reasons to use the block form, as others have pointed out.
···
Is this safe? When will the file be closed? For IO it's said:
"I/O streams are automatically closed when they are claimed by
the garbage collector." Is this true for files as well, (File
is a subclass of IO)?
"Erik Veenstra" <pan@erikveen.dds.nl> schrieb im Newsbeitrag
news:pan.2004.07.22.19.34.08.348106@erikveen.dds.nl...
Consider...
File.new("file.ext", "w").write data
Is this safe? When will the file be closed? For IO it's said:
"I/O streams are automatically closed when they are claimed by
the garbage collector." Is this true for files as well, (File
is a subclass of IO)?
Yes. But you won't know when it is closed. That can be a nuisance if you
have to open the same file multiple times - it may work or not, depending
on the timing of GC. But that's usually a bad choice.
I know you can do...
File.open("file.ext", "w"){|f| f.write data}
..., but the first one is shorter and better readable.
.... and less safe. Use the block form, that's IMHO the most appropriate
thing to do here. It's not much longer also.