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 #  www. j a 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 ava 2  s  .co m
puts f.path 
f.close

Result

Related Topic