new(*args) public

Returns a new IO object (a stream) for the given IO object or integer file descriptor and mode string. See also IO.sysopen and IO.for_fd.

Parameters

fd

numeric file descriptor or IO object

mode

file mode. a string or an integer

opt

hash for specifying mode by name.

Mode

When mode is an integer it must be combination of the modes defined in File::Constants.

When mode is a string it must be in one of the following forms:

  • “fmode”,

  • “fmode:extern”,

  • “fmode:extern:intern”.

extern is the external encoding name for the IO. intern is the internal encoding. fmode must be a file open mode string. See the description of class IO for mode string directives.

When the mode of original IO is read only, the mode cannot be changed to be writable. Similarly, the mode cannot be changed from write only to readable.

When such a change is attempted the error is raised in different locations according to the platform.

Options

opt can have the following keys

:mode

Same as mode parameter

:external_encoding

External encoding for the IO. “-” is a synonym for the default external encoding.

:internal_encoding

Internal encoding for the IO. “-” is a synonym for the default internal encoding.

If the value is nil no conversion occurs.

:encoding

Specifies external and internal encodings as “extern:intern”.

:textmode

If the value is truth value, same as “t” in argument mode.

:binmode

If the value is truth value, same as “b” in argument mode.

:autoclose

If the value is false, the fd will be kept open after this IO instance gets finalized.

Also opt can have same keys in String#encode for controlling conversion between the external encoding and the internal encoding.

Example 1

fd = IO.sysopen("/dev/tty", "w")
a = IO.new(fd,"w")
$stderr.puts "Hello"
a.puts "World"

produces:

Hello
World

Example 2

require 'fcntl'

fd = STDERR.fcntl(Fcntl::F_DUPFD)
io = IO.new(fd, mode: 'w:UTF-16LE', cr_newline: true)
io.puts "Hello, World!"

fd = STDERR.fcntl(Fcntl::F_DUPFD)
io = IO.new(fd, mode: 'w', cr_newline: true,
            external_encoding: Encoding::UTF_16LE)
io.puts "Hello, World!"

Both of above print “Hello, World!” in UTF-16LE to standard error output with converting EOL generated by puts to CR.

Show source
Register or log in to add new notes.