file = Tempfile.new('foo') begin ...do something with file... ensure file.close file.unlink # deletes the temp file end
On POSIX systems it’s possible to unlink a file before closing it. This practice is explained in detail in the Tempfile overview (section “Unlink after creation”); please refer there for more information.
However, unlink-before-close may not be supported on non-POSIX operating systems. Microsoft Windows is the most notable case: unlinking a non-closed file will result in an error, which this method will silently ignore. If you want to practice unlink-before-close whenever possible, then you should write code like this:
# File lib/tempfile.rb, line 230 def unlink # keep this order for thread safeness return unless @tmpname begin if File.exist?(@tmpname) File.unlink(@tmpname) end # remove tmpname from remover @data = @data = nil @tmpname = nil rescue Errno::EACCES # may not be able to unlink on Windows; just ignore end end