Skip to content

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

class method

File.new

(::path | ::int file_name, ?::string | ::int mode, ?::int perm, ?mode: ::Integer | ::String, ?flags: ::Integer, ?external_encoding: ::encoding, ?internal_encoding: ::encoding, ?encoding: ::encoding, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?path: ::path, ?invalid: :replace | nil, ?undef: :replace | nil, ?replace: ::String | nil, ?fallback: ::Hash[::string, ::string] | ^(::String) -> ::string | ::Method | nil, ?xml: :text | :attr | nil, ?cr_newline: bool, ?crlf_newline: bool, ?universal_newline: bool) -> ::File
File.new(path, mode = 'r', permissions = 0666, **options) → file

Opens the file as specified by the given arguments. Creates and returns a new open File object for that file; the opened file is in non-synchronous mode.

Argument path must the string path to an existing filesystem entry:

Example
file = File.new('doc/maintainers.md') # => #<File:doc/maintainers.md>
file.close                            # Clean up.
tty = File.new('/dev/tty')            # => #<File:/dev/tty>
tty.close                             # Clean up.

Note that the caller is responsible for closing the file; see File.open for automatic closing.

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

Example
file = File.new('t.tmp', 'w')          # => #<File:t.tmp>
file.close                             # Clean up.
file = File.new('t.tmp', File::RDONLY) # => #<File:t.tmp>
file.close                             # Clean up.

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

Example
file = File.new('t.tmp', 'w', 0644)    # => #<File:t.tmp>
file.close                             # Clean up.
file = File.new('t.tmp', 'w', 0444)    # => #<File:t.tmp>
file.close                             # Clean up.

Optional keyword arguments options specify:

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