Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

IO.new

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

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

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

Example
IO.new(fd, 'w')         # => #<IO:fd 3>
IO.new(fd, File::WRONLY) # => #<IO:fd 3>

Optional keyword arguments opts specify:

Examples:

Example
IO.new(fd, internal_encoding: nil) # => #<IO:fd 3>
IO.new(fd, autoclose: true)        # => #<IO:fd 3>

Ruby version changes

  1. 3.2
See also .for_fd .open .foreach .pipe also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0