liveBook · Manning

Standard output

As explained in The Well-Grounded Rubyist, Fourth Edition

The standard output stream is the default character stream through which a process writes ordinary textual output.

Standard output is the default character stream for a process's ordinary textual output. Unless redirected, Ruby sends unadorned output such as puts to the terminal through STDOUT and, operationally, $stdout. section 12.1.3 section 12.1.1

STDOUT is a constant referring to an IO object, while $stdout is a reassignable global variable. Reassigning $stdout changes where plain puts writes without replacing the original STDOUT stream. section 12.1.3 section 12.1.1

Ruby exposes several related ways to write output:

  • Use puts for ordinary output with an automatic newline. section 12.1.3
  • Use display for direct string output; it defaults to STDOUT but does not add a newline. section 7.4.1
  • Call print or write on an IO object when newline control matters; write returns the number of bytes written. section 12.1.1
  • Treat IO objects as Enumerable objects when processing input records, although that behavior belongs primarily to STDIN. section 12.1.2
Listing 12.1 Directing all output to a single file
record = File.open("/tmp/record", "w")
old_stdout = $stdout
$stdout = record
$stderr = $stdout
puts "This is a record"
z = 10/0

Redirect $stdout and $stderr to one file, then observe ordinary output and an error message sharing that destination. section 12.1.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines STDOUT as an IO object, connects puts and display to it, and stops short of implementation-level stream internals.
Examples
Uses puts, display, file redirection, and enumerable IO examples to demonstrate output destinations and stream behavior.
What it assumes
Assumes basic Ruby method usage and develops the IO model through keyboard, terminal, and file examples.
What you can do after
Operate/configure standard output by writing with puts or display and redirecting $stdout and $stderr to a file.
How it connects
Connects standard output with standard input, standard error, IO objects, File, and Enumerable behavior.

Also explained in

Compare how 6 books explain standard output →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.