Maintenance Ruby 3.4 gets fixes, but no new features. 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 {
VALUE cmd = check_pipe_command(tmp);
if (!NIL_P(cmd)) {
// TODO: when removed in 4.0, update command_injection.rdoc
rb_warn_deprecated_to_remove_at(4.0, "Calling Kernel#open with a leading '|'", "IO.popen");
argv[0] = cmd;
return rb_io_s_popen(argc, argv, rb_cIO);
}
}
}
}
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.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
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.