Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

Pathname.mktmpdir

Pathname.mktmpdir → new_pathname
Pathname.mktmpdir {|pathname| ... } → object

Creates:

  • A temporary directory via Dir.mktmpdir.

  • A Pathname object that contains the path to that directory.

With no block given, returns the created pathname; the caller should delete the created directory when it is no longer needed (FileUtils.rm_r is a convenient method for the deletion):

Example
pathname = Pathname.mktmpdir
dirpath = pathname.to_s
Dir.exist?(dirpath) # => true
# Do something with the directory.
require 'fileutils'
FileUtils.rm_r(dirpath)

With a block given, calls the block with the created pathname; on block exit, automatically deletes the created directory and all its contents; returns the block’s exit value:

Example
pathname = Pathname.mktmpdir do |p|
  # Do something with the directory.
  p
end
Dir.exist?(pathname.to_s) # => false
See also .glob .new .getwd .pwd also in 4.0 · 3.4