Difference between $stdout and STDOUT in Ruby

jrdioko picture jrdioko · Jul 12, 2011 · Viewed 35.2k times · Source

In Ruby, what is the difference between $stdout (preceded by a dollar sign) and STDOUT (in all caps)? When doing output redirection, which should be used and why? The same goes for $stderr and STDERR.

Edit: Just found a related question.

Answer

Brian picture Brian · Jul 13, 2011

$stdout is a global variable that represents the current standard output. STDOUT is a constant representing standard output and is typically the default value of $stdout.

With STDOUT being a constant, you shouldn't re-define it, however, you can re-define $stdout without errors/warnings (re-defining STDOUT will raise a warning). for example, you can do:

$stdout = STDERR

Same goes for $stderr and STDERR


So, to answer the other part of your question, use the global variables to redirect output, not the constants. Just be careful to change it back further on in your code, re-defining global variables can impact other parts of your application.