Overview

12 File and I/O operations

Ruby’s file and I/O model is built around the idea that streams, devices, and files are objects, so ordinary object-oriented habits carry over naturally into input, output, and system interaction. Standard input, output, and error are available as IO objects, and Ruby’s familiar methods such as puts, print, gets, and write work through those streams. The chapter also shows that IO objects can behave like enumerables, which means you can iterate over input line by line and use familiar collection-style operations while controlling how records are separated.

The chapter then develops file handling through the File class, which extends IO and supports reading and writing in several granularities, from whole-file reads to line, character, and byte-level access. It explains how file position can be queried and changed with pos, rewind, and seek, how class-level helpers like File.read and File.readlines simplify common tasks, and why higher-level methods are generally preferable to low-level sysread and syswrite. Writing is covered as persistence, including opening files in write or append mode and using blocks with File.open to automatically close handles and keep file operations neatly scoped.

Beyond basic file access, the chapter explores querying file and directory properties with File, FileTest, File::Stat, and Dir, along with directory traversal through entries and globbing. It highlights standard library tools that make file work more practical: FileUtils for copying, moving, removing, and dry-running operations; Pathname for treating paths as structured objects; StringIO for testing and in-memory stream behavior; and open-uri for reading remote resources through the same interface used for local files. Overall, the chapter presents Ruby file and I/O work as consistent, expressive, and strongly object oriented, while emphasizing safe habits, efficiency, and the usefulness of the standard library.

Summary

  • The File and IO classes do much of the file and I/O work.
  • File and IO both mix in Enumerable, with File being a subclass of IO.
  • The STDIN, STDOUT, and STDERR objects give you access to those system I/O streams.
  • The FileUtils module provides a package of useful utilities for creating, moving, deleting, and otherwise manipulating files, with many of its methods’ names based on the syntax of system/shell file-related commands.
  • The Pathname class allows for easy, extended operations on strings representing file system paths.
  • The StringIO class lets you address a string as if it were an I/O stream.
  • The OpenURI module makes it easy to “open” documents on the network.

FAQ

What is the role of the IO class in Ruby’s file and I/O system?

The IO class represents input and output streams such as files, keyboards, screens, and other devices. Many higher-level classes and methods, including File, build on IO’s behavior.

How do STDIN, STDOUT, and STDERR differ from $stdin, $stdout, and $stderr?

STDIN, STDOUT, and STDERR are constants for the default standard streams. The lowercase versions are global variables that can be reassigned, letting you redirect input, output, or error streams without losing the original ones.

What is the difference between puts, print, and write on an IO object?

puts adds a newline automatically and returns nil. print does not automatically add a newline and also returns nil. write does not add a newline and returns the number of bytes written.

How does File.open with a block help manage file resources?

When File.open is given a block, the opened file is passed into the block and automatically closed when the block ends. This is a common Ruby pattern for safe and tidy file handling.

What is the difference between gets and readline when reading from a file?

gets returns the next line or nil at end of file. readline also reads one line, but raises EOFError if the end of the file is reached.

How do you read a file by bytes or characters in Ruby?

You can use getc for one character and getbyte for one byte. Their stricter versions, readchar and readbyte, raise EOFError at end of file instead of returning nil.

How can you move around inside a file using pos, rewind, and seek?

rewind moves the file pointer back to the beginning. pos reports or sets the current byte position. seek moves the pointer relative to the start, current position, or end of the file using constants like IO::SEEK_SET, IO::SEEK_CUR, and IO::SEEK_END.

What is the purpose of FileTest and File::Stat?

FileTest provides boolean and query methods such as exist?, directory?, readable?, and size. File::Stat returns an object with file metadata like size, permissions, and access times.

How do Dir.entries and Dir.glob differ?

Dir.entries returns all entries in a directory, including ., .., and hidden dotfiles. Dir.glob supports wildcard matching and usually excludes hidden dotfiles unless you use flags such as File::FNM_DOTMATCH.

What are FileUtils, Pathname, StringIO, and open-uri used for?

FileUtils provides high-level file operations like copy, move, and delete. Pathname makes path manipulation more object oriented. StringIO lets strings behave like I/O objects, which is useful for testing. open-uri lets you open URLs like files and read remote content through an I/O-like interface.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Well-Grounded Rubyist, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Well-Grounded Rubyist, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Well-Grounded Rubyist, Fourth Edition ebook for free