在Ruby中,$stderr
指的是currently used作为stderr的输出流,而STDERR
指的是default stderr流.很容易将不同的输出流临时分配给$stderr
.
require "stringio"
def capture_stderr
# The output stream must be an IO-like object. In this case we capture it in
# an in-memory IO object so we can return the string value. You can assign any
# IO object here.
previous_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
# Restore the previous value of stderr (typically equal to STDERR).
$stderr = previous_stderr
end
现在,您可以执行以下操作:
captured_output = capture_stderr do
# Does not output anything directly.
$stderr.puts "test"
end
captured_output
#=> "test\n"
同样的原理也适用于$stdout
和STDOUT
.