Skip to content

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

class method

File.new

(::string | ::_ToPath | ::int file_name, ?::string | ::int mode, ?::int perm) -> ::File
File.new(path, mode = 'r', perm = 0666, **opts) → file

Opens the file at the given path according to the given mode; creates and returns a new File object for that file.

The new File object is buffered mode (or non-sync mode), unless filename is a tty. See IO#flush, IO#fsync, IO#fdatasync, and IO#sync=.

Argument path must be a valid file path:

Example
f = File.new('/etc/fstab')
f.close
f = File.new('t.txt')
f.close

Optional argument mode (defaults to ‘r’) must specify a valid mode; see Access Modes:

Example
f = File.new('t.tmp', 'w')
f.close
f = File.new('t.tmp', File::RDONLY)
f.close

Optional argument perm (defaults to 0666) must specify valid permissions see File Permissions:

Example
f = File.new('t.tmp', File::CREAT, 0644)
f.close
f = File.new('t.tmp', File::CREAT, 0444)
f.close

Optional keyword arguments opts specify:

See also .mtime .open .mkfifo .owned? also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0