Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

IO.new

(::int fd, ?::string | ::int mode, ?path: ::string?, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String) -> ::IO
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
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:

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.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0