TIL: tempfile in ruby, use it for easy garbage collection afterwards
Today, I was working on a script at work where I ultimately needed to export a 2MB file and although this isn’t a large file, I know I will forget about getting rid of it so while searching around, I came across tempfile.
Tempfile simply will be garbage collected at some time because the file is stored in /tmp
and you can make your own copy if you need it. Here’s an example from the ruby docs:
require 'tempfile'
file = Tempfile.new('foo')
file.path # => A unique filename in the OS's temp directory,
# e.g.: "/tmp/foo.24722.0"
# This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read # => "hello world"
file.close
file.unlink # deletes the temp file
Make sure to run file.unlink
if you want it to be deleted right away.
Comments ()