Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close and delete a file in Ruby?

Tags:

file

ruby

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.

like image 586
blackghost Avatar asked Aug 12 '14 16:08

blackghost


1 Answers

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
like image 191
konsolebox Avatar answered Sep 28 '22 10:09

konsolebox