Search code examples
rubystdoutstderroutput-redirect

Difference between $stdout and STDOUT in Ruby


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.


Solution

  • $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.