The IO Class

The basis for all input and output in Ruby is the IO class, which represents an input/output (I/O) stream of data in the form of bytes. Standard streams include standard input stream ($stdin) or the keyboard; standard output stream ($stdout), the display or screen; and standard error output stream ($stderr), which is also the display by default. IO is closely associated with the File class, and File is the only standard subclass of IO in Ruby. I'll show you a sampling of IO code.

To create a new I/O stream named ios, use the new method. The first argument is 1 which is the numeric file descriptor for standard input. Standard input can also be represented by the predefined Ruby variable $stdin (see Table 8). The optional second argument, w, is a mode string meaning write:

ios = IO.new( 1, "w" )

ios.puts "IO, IO, it's off to the computer lab I go."

$stdout.puts "Do you copy?"

Table 8. Standard streams

Stream description

File descriptor

Predefined Ruby variable

Ruby environment variable

Standard input stream

0

$stdin

STDIN

Standard output stream

1

$stdout

STDOUT

Standard error output stream

2

$stderr

STDERR

Other mode strings include r or read-only (the default), r+ for read-write, and w for write-only. For details on all available modes, see Table 9.

Table 9. I/O modes

Mode

Description

r

Read-only. Starts at the beginning of the file (default mode).

r+

Read-write. Starts at the beginning of the file.

w

Write-only. Truncates existing file to zero length, or creates a new file for writing.

w+

Read-write. Truncates existing file to zero length, or creates a new file for reading and writing.

a

Write-only. Starts at the end of file, if the file exists; otherwise, creates a new file for writing.

a+

Read-write, starts at the end of the file, if file exists; otherwise, creates a new file for reading and writing.

b

Binary file mode. May appear with any of the modes listed in this table. DOS/Windows only.

With the IO instance method fileno, you can test what the numeric file descriptor is for your I/O stream (to_i also works):

ios.fileno # => 1
ios.to_i # => 1

$stdout.fileno # => 1

You can also write strings to the stream (buffer) with the << method, then flush the buffer with flush:

ios << "Ask not " << "for whom the bell tolls." << " -John
Donne"

ios.flush # => Ask not for whom the bell tolls. -John
Donne

Finally, close the stream with close (this also flushes any pending writes):

ios.close