В Ruby $stderr
относится к выходному потоку, который в настоящее время используется в качестве stderr, тогда как STDERR
является потоком по умолчанию 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
.