Ruby - Creating Temporary Files

Introduction

Operating systems have "temporary" directory where temporary files can be stored.

Temporary files are created briefly during a program's execution.

Dir.tmpdir provides the path to the temporary directory

Demo

require 'tmpdir' 
puts Dir.tmpdir

Result

You can use Dir.tmpdir with File.join to create a platform-independent way of creating a temporary file:

Demo

require 'tmpdir' 
tempfilename = File.join(Dir.tmpdir, "myapp.dat") 
tempfile = File.new(tempfilename, "w") 
tempfile.puts "This is only temporary" 
tempfile.close #  w  w  w  .ja  v a 2s . com
File.delete(tempfilename)

This code creates a temporary file, writes data to it, and deletes it.

Ruby's standard library includes a library called tempfile that can create temporary files for you:

Demo

require 'tempfile' 
f = Tempfile.new('myapp') 
f.puts "Hello" # from  w  w  w  .j a  v a  2s .c  om
puts f.path 
f.close

Result

Related Topic