开发者

Ruby stdio consts and globals, what are the uses?

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 (som开发者_如何学编程e 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:

#!/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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜