Temporary files and directories in Ruby

File

Create a temporary file in your current directory:

require 'tempfile'

Tempfile.create('', Dir.pwd) do |file|
  puts File.path(file)

  File.write(file, 'I am temporary!')
  puts File.read(file)
end

Directory

For directory it’s similar, but no require needed:

Dir.mktmpdir(nil, Dir.pwd) do |dir|
  puts File.path(dir)
end