This post originated from an RSS feed registered with Ruby Buzz
by Eric Hodel.
Original Post: $stdout vs STDOUT
Feed Title: Segment7
Feed URL: http://blog.segment7.net/articles.rss
Feed Description: Posts about and around Ruby, MetaRuby, ruby2c, ZenTest and work at The Robot Co-op.
You may have noticed me using both $stdout and STDOUT in my last post and been puzzled by how I could use both.
When Ruby starts up the process’ standard output file descriptor is stored in both the constant STDOUT and the global variable $stdout. STDOUT holds the process’ original stdout while $stdout is reassignable. Kernel#puts and friends use $stdout for to write their output, not STDOUT.
To be most-friendly, when you want to redirect stdout you should assign to $stdout instead of fiddling with STDOUT. When outputting to an explicit file descriptor, use $stdout or $stderr instead of STDOUT or STDERR.
STDOUT can only be changed by calling IO#reopen, but you can assign any object that responds to #write to $stdout, which is what made my ThreadOut hack work.