chapter twelve

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. This is great for consistency—as your programs grow and begin interacting with other systems, you can fall back on your “(very nearly) everything is an object” understanding of Ruby and apply it to the utilities described in this chapter. 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.

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

12.1.1 The IO class

12.1.2 IO objects as enumerables

12.1.3 STDIN, STDOUT, STDERR

12.1.4 A little more about keyboard input

12.2 Basic file operations

12.2.1 The basics of reading from files

12.2.2 Line-based file reading

12.2.3 Byte- and character-based file reading

12.2.4 Seeking and querying file position

12.2.5 Reading files with File class methods

12.2.6 Writing to files

12.2.7 Using blocks to scope file operations

12.2.8 File enumerability

12.2.9 File I/O exceptions and errors

12.3 Querying IO and File objects

12.3.1 Getting information from the File class and the FileTest module

12.3.2 Deriving file information with File::Stat

12.4 Directory manipulation with the Dir class

12.4.1 Reading a directory’s entries

12.4.2 Directory manipulation and querying

12.5 File tools from the standard library

12.5.1 The FileUtils module

12.5.2 The Pathname class

12.5.3 The StringIO class

12.5.4 The open-uri library

12.6 Summary