new
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 |
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 combination of the directives. See the description of class IO for a description of the 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. If such a wrong change is directed, timing where the error actually occurs is different according to the platform.
Options
opt can have the following keys
:mode |
same as mode parameter |
external encoding for the IO. “-” is a synonym for the default external 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. |
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.
Example1
fd = IO.sysopen("/dev/tty", "w") a = IO.new(fd,"w") $stderr.puts "Hello" a.puts "World"
produces:
Hello World
Example2
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.