Robert Klemme
2/10/2006 4:55:00 PM
Eric Jacoboni wrote:
> Hi,
>
> If i use File::open to open/create a file objet, and if i use a block
> with it, the file will be automatically close when the block ends:
>
> Now, considering this buggy snippet:
>
> begin
> File.open("my_file") do |fic|
> fic.puts("bla")
> end
> rescue Exception => e
> STDERR.puts(e)
> exit(1)
> end
>
> Here, the "not opened for writing" exception will be raised, the block
> end will never be reached and the file will remain opened, isn't it ?
> To circumvent this, i have to make fic a global variable and put the
> appropriate code in a ensure clause (or open a begin/ensure in the
> File.open block to close the file... too bad)
>
> So, my question is: what's the benefit of this idiom versus this one:
>
> begin
> fd = File.new("my_file")
> ...
> rescue Exception => e
> STDERR.puts(e)
> exit(1)
> ensure
> fd.close if fd and not fd.closed?
> end
>
> Is there something i've missed?
Yes, as Grennady pointed out. The benefit of using File#open with a block
is exactly that you do not have to do the closing yourself. Less code,
less errors.
Btw, your first example is overly complex. This does the same:
File.open("my_file") do |fic|
fic.puts("bla")
end
17:53:40 [~]: ruby -e 'File.open("dsdsd") {|io| p io}' ; echo $?
-e:1:in `initialize': No such file or directory - dsdsd (Errno::ENOENT)
from -e:1
1
17:53:55 [~]:
Kind regards
robert