STDOUT
is a constant that represents the standard output, which is an IO
object. And $stdout
is a global variable whose default values is usually STDOUT
itself, by default, both point to the same object:
$stdout.object_id == STDOUT.object_id => true
If you call a method on one of them, the other one will be affected. So if you call a method using $stdout
it will also take effect on STDOUT
. Calling reopen
on $stdout
will affect STDOUT
as well (even if it's a constant).
If you want to redirect output to a file temporarily and restore it then to the standard output, you should assign $stdout
a new IO
object:
$stdout = File.open('/path/to/file', 'w:UTF-8')
puts "this will go to the file"
$stdout = STDOUT
puts "this will go to standard output!"
See also the following questions: