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?
A more elaborate version of this function is in use in production code:
It is used in unit tests that want to know what was written to the console using
printorputs.The
$variables let you give Ruby different IO objects for stdout, stdin, stderr:the constants make it easy to get the
$variables back to their original (when your program started) value: