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
io.c
View on GitHub ↗
static VALUE
rb_file_initialize(int argc, VALUE *argv, VALUE io)
{
if (RFILE(io)->fptr) {
rb_raise(rb_eRuntimeError, "reinitializing File");
}
VALUE fname, vmode, vperm, opt;
int posargc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
if (posargc < 3) { /* perm is File only */
VALUE fd = rb_check_to_int(fname);
if (!NIL_P(fd)) {
return io_initialize(io, fd, vmode, opt);
}
}
return rb_open_file(io, fname, vmode, vperm, opt);
}
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: