Method: IO#initialize

Defined in:
io.c

#new(fd, mode = 'r', **opts) ⇒ IO

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):

fd = IO.sysopen('t.rus', '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>


9493
9494
9495
9496
9497
9498
9499
9500
9501
# File 'io.c', line 9493

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);
}