Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
IO.new
static VALUE
rb_io_initialize(int argc, VALUE *argv, VALUE io)
{
VALUE fnum, vmode;
VALUE opt;
rb_scan_args(argc, argv, "11:", &fnum, &vmode, &opt);
return io_initialize(io, fnum, vmode, opt);
}
Creates and returns a new IO object (file stream) from a file descriptor.
IO.new may be useful for interaction with low-level libraries. For higher-level interactions, it may be simpler to create the file stream using File.open.
Argument fd must be a valid file descriptor (integer):
path = 't.tmp' fd = IO.sysopen(path) # => 3 IO.new(fd) # => #<IO:fd 3>
The new IO object does not inherit encoding (because the integer file descriptor does not have an encoding):
File.read('t.ja') # => "こんにちは" fd = IO.sysopen('t.ja', 'rb') io = IO.new(fd) io.external_encoding # => #<Encoding:UTF-8> # Not ASCII-8BIT.
Optional argument mode (defaults to ‘r’) must specify a valid mode; see Access Modes:
IO.new(fd, 'w') # => #<IO:fd 3> IO.new(fd, File::WRONLY) # => #<IO:fd 3>
Optional keyword arguments opts specify:
Examples:
IO.new(fd, internal_encoding: nil) # => #<IO:fd 3> IO.new(fd, autoclose: true) # => #<IO:fd 3>
Ruby version changes
-
3.2
-
Introduce
IO.new(..., path:)and promoteFile#pathtoIO#path. [Feature #19036]
-