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





