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.
require 'tempfile'
class TempSample
temp_file = Tempfile.new('random')
1.upto(50) do
num = rand(50) # random number generation in ruby
temp_file.print(num,"\n") # print number and newline to the file
end
temp_file.flush # flush it so that you can see it using cat
gets # wait for user input. At this point you can see a temp file /tmp
# The filename in my case was random.5789.0
end
require 'tempfile' class TempSample temp_file = Tempfile.new('random') 1.upto(50) do num = rand(50) # random number generation in ruby temp_file.print(num,"\n") # print number and newline to the file end temp_file.flush # flush it so that you can see it using cat gets # wait for user input. At this point you can see a temp file /tmp # The filename in my case was random.5789.0 end
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’)