iTranslated by AI
STDOUT and $stdout in Ruby
I'm writing this because STDOUT and $stdout were discussed at a recent Ruby-dev office hour.
The discussion apparently started because $stdout is available in Ractor while STDOUT is not, but I'll set Ractor aside as I'm not too familiar with it.
In Ruby, we have constants (STDIN, STDOUT, STDERR) and global variables ($stdin, $stdout, $stderr) to represent standard input, output, and error.
Although I refer to STDOUT / $stdout below, the same applies to STDIN / $stdin and STDERR / $stderr.
Immediately after the Ruby process starts, they point to the same object.
STDOUT.__id__ # => 7984
$stdout.__id__ # => 7984
Since $stdout is a variable, it can be reassigned. Doing so naturally makes them different objects.
$stdout = File.open('/tmp/hoge.out', 'a')
$stdout == STDOUT #=> false
Since Ruby's p and puts output to $stdout, you can perform something similar to redirection just by assigning an IO object to $stdout.
Therefore, you should generally use $stdout.
So, what is STDOUT for?
Since it is a constant, it cannot be reassigned (well, it is Ruby, so you actually can, but surely no one would do that).
In other words, even if you reassign and change $stdout, STDOUT continues to maintain file descriptor 1 (similarly, STDIN maintains 0, and STDERR maintains 2).
$stdout = File.open('/tmp/hoge.out', 'a')
$stdout.fileno #=> 5
STDOUT.fileno #=> 1
Therefore, it can be used to restore $stdout.
$stdout = STDOUT
By the way, when starting another program from a Ruby program, $stdout is not inherited.
If you execute the code below, the output of ls will not appear in hoge.out but will be displayed on the terminal. This is because file descriptor 1 remains unchanged.
$stdout = File.open('/tmp/hoge.out', 'a')
system('ls')
If you want to pass the redirection to another program, you need to change STDOUT, which corresponds to file descriptor 1.
In the past, people used to write it like this:
pid = fork do
STDOUT.reopen('/tmp/hoge.out', 'a')
exec('ls')
end
Process.wait(pid)
Usually, $stdout.reopen would work as well, but STDOUT is safer because $stdout might have been modified elsewhere.
However, in modern Ruby, you can easily specify redirection using system options without having to use fork & exec:
system('ls', out: ['/tmp/hoge.out', 'a'])
Therefore, there might not be many situations left where you need to use the constant anymore.
According to rumors, some people are misled by the idea that "global variables shouldn't be used in programs" and refuse to use $stdout at all costs. However, since it represents a global object within the program, using a global variable is perfectly logical, so feel free to use it without worry.
Discussion