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.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

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.

See also .new .owned? .mtime .path also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0