Chapter 12. File and I/O operations

 

This chapter covers

  • Keyboard input and screen output
  • The IO and File classes
  • Standard library file facilities, including FileUtils and Pathname
  • The StringIO and open-uri library features

As you’ll see once you dive in, Ruby keeps even file and I/O operations object-oriented. Input and output streams, like the standard input stream or, for that matter, any file handle, are objects. Some I/O-related commands are more procedural: puts, for example, or the system method that lets you execute a system command. But puts is only procedural when it’s operating on the standard output stream. When you puts a line to a file, you explicitly send the message “puts” to a File object.

The memory space of a Ruby program is a kind of idealized space, where objects come into existence and talk to each other. Given the fact that I/O and system command execution involve stepping outside this idealized space, Ruby does a lot to keep objects in the mix.

You’ll see more discussion of standard library (as opposed to core) packages in this chapter than anywhere else in the book. That’s because the file-handling facilities in the standard library—highlighted by the FileUtils, Pathname, and StringIO packages—are so powerful and so versatile that they’ve achieved a kind of quasi-core status. The odds are that if you do any kind of file-intensive Ruby programming, you’ll get to the point where you load those packages almost without thinking about it.

12.1. How Ruby’s I/O system is put together

12.2. Basic file operations

12.3. Querying IO and File objects

12.4. Directory manipulation with the Dir class

12.5. File tools from the standard library

12.6. Summary