liveBook · Manning

$stderr

As explained in The Well-Grounded Rubyist, Fourth Edition

$stderr is Ruby's reassignable global variable that refers to the current standard error stream.

$stderr is Ruby’s reassignable global variable for the current standard error stream. Unlike the STDERR constant, it can be assigned a different IO object, allowing a program to redirect error output without losing the original stream. section 12.1.3 section 12.1.1

Redirecting errors to a file

record = File.open("/tmp/record", "w") $stdout = record $stderr = $stdout puts "This is a record" z = 10/0 Both ordinary output and the resulting division-by-zero message are written to the file because each global variable points to the same handle. section 12.1.3

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

Shows $stderr being assigned to the same file handle as $stdout before ordinary and failing operations run. section 12.1.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains reassignment, IO-handle behavior, and combined output redirection, but does not develop restoration or lifecycle details.
Examples
Uses STDERR.puts, file redirection, and a division-by-zero exception to demonstrate error output.
What it assumes
Assumes basic Ruby I/O familiarity while establishing IO objects, standard streams, and constants versus global variables.
What you can do after
Operate/configure Ruby output by assigning $stderr to an alternative IO stream.
How it connects
Connects standard error streams with global variables, IO objects, STDOUT, STDIN, and file 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.