Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Kernel#open
(::String name, ?::String mode, ?::Integer perm) -> ::IO?
[T] (::String name, ?::String mode, ?::Integer perm) { (::IO) -> T } -> T
open(path, mode = 'r', perm = 0666, **opts) → io or nil
open(path, mode = 'r', perm = 0666, **opts) {|io| ... } → obj
io.c
View on GitHub ↗
static VALUE
rb_f_open(int argc, VALUE *argv, VALUE _)
{
ID to_open = 0;
int redirect = FALSE;
if (argc >= 1) {
CONST_ID(to_open, "to_open");
if (rb_respond_to(argv[0], to_open)) {
redirect = TRUE;
}
else {
VALUE tmp = argv[0];
FilePathValue(tmp);
if (NIL_P(tmp)) {
redirect = TRUE;
}
else {
argv[0] = tmp;
}
}
}
if (redirect) {
VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
return rb_io_s_open(argc, argv, rb_cFile);
}
Creates an IO object connected to the given file.
With no block given, file stream is returned:
Example
open('t.txt') # => #<File:t.txt>
With a block given, calls the block with the open file stream, then closes the stream:
Example
open('t.txt') {|f| p f } # => #<File:t.txt (closed)>
Output:
Example
#<File:t.txt>
See File.open for details.
Ruby version changes
-
4.0
-
A deprecated behavior, process creation by
Kernel#openwith a leading|, was removed. [Feature #19630]
-