Redirecting Standard Output

Earlier in the chapter, we saw how methods such as print and puts operated implicitly on $stdout. This is an important point—that is, that they operate on the variable $stdout rather than the fixed STDOUT.

This means that if we reassign $stdout to some other value, all calls to these methods—even ones made by libraries and other code that isn’t our own—will be passed to whatever we replaced $stdout with. This enables us to neatly, in a single line, redirect all of the output of our program to another place. Let’s take a look at two practical uses for this.

Redirecting All Output to a File

The only expectations that Ruby has of $stdout is that it be an IO object. As we saw in IO: Ruby’s Input/Output Class, the

Get Text Processing with Ruby 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.