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 |
|
|
Standard output stream | 1 |
|
|
Standard error output stream | 2 |
|
|
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 |
|---|---|
| Read-only. Starts at the beginning of the file (default mode). |
| Read-write. Starts at the beginning of the file. |
| Write-only. Truncates existing file to zero length, or creates a new file for writing. |
| Read-write. ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access