Say that I open a file in Ruby like this:
f = File.open('diagram.txt', 'r')
Right now, in order to close and delete that file I have this code:
begin
f = File.open('diagram.txt', 'r')
ensure
if !f.nil? && File.exist?(f)
f.close unless f.closed?
File.delete(f)
end
end
I found this code to be too complicated, and the File.exist?(f)
would fail if the f is closed already. So, what is the correct approach to avoid the closing and deleting of the file raising exceptions?
Note: I know that passing a block to File.open will close the file directly, however, I am looking for the general approach of closing and deleting.
Why not just delete the file after closing and not depending from the object but from the filename itself?
begin
f = File.open('diagram.txt', 'r')
ensure
f.close unless f.nil? or f.closed?
File.delete('diagram.txt') if File.exists? 'diagram.txt'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With