A Ruby temporary file example

Problem: There are times when you're writing Ruby code that you need to be able to create and write information to a temporary file. If you write your own code to do this, there are a number of decisions to be made (see below), and you'd like to avoid all of that mess.

Solution: Use the Ruby Tempfile class to handle the grunt work for you.

To demonstrate the Ruby Tempfile class, here's the output from an irb session where I walk through the process of creating a temporary file, writing to it, flushing the buffer, and then closing my irb session. During this process I had a second terminal window open to look at the temporary file, and I've added comments to this irb output showing what I could see from that second window.

Here's my irb session:

>> require 'tempfile'
=> true

# Tempfile requires one argument, which will become part of your filename
>> tmp = Tempfile.new('fred')
=> #<File:/var/folders/h5/h59HESVvEmG+3I4Q8lOAxE+++TI/-Tmp-/fred.1637.0>

# in my second terminal i can see that this file exists

# use the path method if you need to know where the file is
# within your code
>> tmp.path
=> "/var/folders/h5/h59HESVvEmG+3I4Q8lOAxE+++TI/-Tmp-/fred.1637.0"

# write something to the file
>> tmp << "Just testing\n"
=> #<File:/var/folders/h5/h59HESVvEmG+3I4Q8lOAxE+++TI/-Tmp-/fred.1637.0>

# the file size was showing up at zero so i called the
# flush method
>> tmp.flush
=> #<File:/var/folders/h5/h59HESVvEmG+3I4Q8lOAxE+++TI/-Tmp-/fred.1637.0>

# the file now had my string in it.
>> tmp.close
=> nil

# after closing the file it was still on the disk.
# after i exited my ruby session, as shown next,
# the file was automatically cleaned up for me.
>> exit


As you can see the Ruby Tempfile class does several nice things for you:

  • It creates a filename somewhere in the current system's temporary folder structure.
  • It opens the file for write mode.
  • It cleans up the file when your Ruby script exits.

It sure is nice to have a class available to help you create temporary files like this.