Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Tempfile#delete
# File tmp/rubies/ruby-3.4.1/lib/tempfile.rb, line 323
def unlink
return if @unlinked
begin
File.unlink(__getobj__.path)
rescue Errno::ENOENT
rescue Errno::EACCES
# may not be able to unlink on Windows; just ignore
return
end
@finalizer_manager.unlinked = true
@unlinked = true
end
Alias of #unlink
Unlinks (deletes) the file from the filesystem. One should always unlink the file after using it, as is explained in the “Explicit close” good practice section in the Tempfile overview:
file = Tempfile.new('foo') begin # ...do something with file... ensure file.close file.unlink # deletes the temp file end
Unlink-before-close
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 = Tempfile.new('foo') file.unlink # On Windows this silently fails. begin # ... do something with file ... ensure file.close! # Closes the file handle. If the file wasn't unlinked # because #unlink failed, then this method will attempt # to do so again. end