Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Tempfile.create

create(basename="", tmpdir=nil, mode: 0, **options) { |tmpfile| ... }

Creates a file in the underlying file system; returns a new File object based on that file.

With no block given and no arguments, creates and returns file whose:

  • Class is File (not Tempfile).

  • Directory is the system temporary directory (system-dependent).

  • Generated filename is unique in that directory.

  • Permissions are 0600; see File Permissions.

  • Mode is 'w+' (read/write mode, positioned at the end).

With no block, the file is not removed automatically, and so should be explicitly removed.

Example:

Example
f = Tempfile.create     # => #<File:/tmp/20220505-9795-17ky6f6>
f.class                 # => File
f.path                  # => "/tmp/20220505-9795-17ky6f6"
f.stat.mode.to_s(8)     # => "100600"
File.exist?(f.path)     # => true
File.unlink(f.path)
File.exist?(f.path)     # => false

Argument basename, if given, may be one of:

  • A string: the generated filename begins with basename:

    Example
    Tempfile.create('foo') # => #<File:/tmp/foo20220505-9795-1gok8l9>
    
  • An array of two strings [prefix, suffix]: the generated filename begins with prefix and ends with suffix:

    Example
    Tempfile.create(%w/foo .jpg/) # => #<File:/tmp/foo20220505-17839-tnjchh.jpg>
    

With arguments basename and tmpdir, the file is created in directory tmpdir:

Example
Tempfile.create('foo', '.') # => #<File:./foo20220505-9795-1emu6g8>

Keyword arguments mode and options are passed directly to method File.open:

  • The value given with mode must be an integer, and may be expressed as the logical OR of constants defined in File::Constants.

  • For options, see Open Options.

With a block given, creates the file as above, passes it to the block, and returns the block’s value; before the return, the file object is closed and the underlying file is removed:

Example
Tempfile.create {|file| file.path } # => "/tmp/20220505-9795-rkists"

Related: Tempfile.new.

See also .new .open also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0