Using temporary files in Ruby - Tempfile.new

For certain programming solutions, you might need a temporary file. Different operating systems store temporary files in different locations. Also you don’t want to explicitly name the file since that is irrelevant in the program. How do you ensure that there are no filename conflicts? The solution for all these is to use library for temp file processing.

Ruby comes a with a default library ‘tempfile’ for handling temporary file creation. Given a filename prefix, it creates a temporary file in the following format.

[prefix]-[process].[unique_number]

This ensures that there is no conflict in creating multiple temporary files in the same directory. Once your program terminates the temporary file is automatically deleted. Also by default, the temporary file is created in the operating system’s temporary folder (In my ubuntu system it is /tmp).

In the following program, a temporary file with prefix ‘random’ to store 50 random numbers is created. When the program terminates you cannot see the temp file. Hence I have added a ‘gets’ which stops for user input. In my case I could see a temporary file named ‘random.5789.0′ under \tmp dir.

If you want to the temp file in a specific directory, you can pass the directory name as the second parameter to new. For example - Tempfile.new(’new1′,’/usr/home/jay’)

Leave a Reply