也许这会有所帮助:
require 'stringio'
str_stdout, str_stderr = (1..2).map{ StringIO.new }
puts "redirecting outputs"
old_stdout, old_stderr = $stdout, $stderr
$stdout, $stderr = str_stdout, str_stderr
STDOUT.puts "This is written to the old STDOUT"
STDERR.puts "This is written to the old STDERR"
$stdout.puts "This is written to str_stdout"
$stderr.puts "This is written to str_stderr"
puts 'this is output via "puts"'
`date`
`date >&2` # this is output to stderr
STDOUT.puts "resetting STDOUT and STDERR"
$stdout, $stderr = old_stdout, old_stderr
str_stdout.rewind
str_stderr.rewind
puts str_stdout.read
puts str_stderr.read
哪个输出:
redirecting outputs
This is written to the old STDOUT
This is written to the old STDERR
Mon Jul 8 21:51:19 MST 2013
resetting STDOUT and STDERR
This is written to str_stdout
this is output via "puts"
This is written to str_stderr
使用调试器或 PRY 查看各种输出何时发生的单步操作。