Input/Output

An IO object is a stream: a readable source of bytes or characters or a writable sink for bytes or characters. The File class is a subclass of IO. IO objects also represent the “standard input” and “standard output” streams used to read from and write to the console. The stringio module in the standard library allows us to create a stream wrapper around a string object. Finally, the socket objects used in networking (described later in this chapter) are also IO objects.

Opening Streams

Before we can perform input or output, we must have an IO object to read from or write to. The IO class defines factory methods new, open, popen, and pipe, but these are low-level methods with operating system dependencies, and they are not documented here. The subsections that follow describe more common ways to obtain IO objects. (And Networking includes examples that create IO objects that communicate across the network.)

Opening files

One of the most common kinds of IO is the reading and writing of files. The File class defines some utility methods (described below) that read the entire contents of a file with one call. Often, however, you will instead open a file to obtain a File object and then use IO methods to read from or write to the file.

Use File.open (or File.new) to open a file. The first argument is the name of the file. This is usually specified as a string, but in Ruby 1.9, you can use any object with a to_path method. Filenames are interpreted relative to the current working ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.