Question

Ruby has constants and global variables for stdio.

Namely, the consts STDIN, STDOUT, STDERR, and their variable counterparts, $stdin, $stdout, $stderr.

I understand the difference between a constant and a variable. I know the constants are immutably set to the file descriptors at the moment the script was exec'd.

I also understand that you can change (some of) the variables at runtime.

I'm curious regarding practical uses of such feature. Why would you want to do it? What can you achieve?

Seeing some sample code, or even just use cases, extracted from real world projects would be awesome.


Update: From what I gather so far, it seems that when writing your own libraries/programs, you should prefer to use the variables over the constants, so that its users can further muck with it. Right?

Was it helpful?

Solution

A more elaborate version of this function is in use in production code:

#!/usr/bin/env ruby -rstringio

def capture_stdout
  $stdout = StringIO.new
  begin
    yield
    $stdout.string
  ensure
    $stdout = STDOUT
  end
end

output = capture_stdout do
  print "Line"
  puts " 1"
end

p output     # => "Line 1\n"

It is used in unit tests that want to know what was written to the console using print or puts.

The $ variables let you give Ruby different IO objects for stdout, stdin, stderr:

$stdout = buffer

the constants make it easy to get the $ variables back to their original (when your program started) value:

$stdout = STDOUT

OTHER TIPS

Matsumoto's book on it seems to give the answer. Quote from 9.7.1.4 Predefined streams: "Global functions like print and puts write to $stdout by default. If a script alters the value of this global variable, it will change the behavior of those methods."

It sounds to me as if the idea is to simply allow an easy solution to a possibly poorly implemented program.

$stderr = File.open 'error.log', 'w'

All errors will be written to error.log

You can send part of your output to a file and then dump it back to the console when you're done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top