Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
File.open
(::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) -> instance
[T] (::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) -> T } -> T
File.open(path, mode = 'r', permissions = 0666, **options) → file
File.open(path, mode = 'r', permissions = 0666, **options) {|file| ... } → object
io.c
View on GitHub ↗
static VALUE
rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
VALUE io = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
Creates a new File object via File.new with the given arguments.
With no block given, returns the File object.
With a block given, calls the block with the File object, closes the File object, and returns the block’s value:
Example
File.open('doc/maintainers.md') {|file| file.size } # => 14900
Note that the File object is automatically closed even if the block raises an exception.