I\'d like to temporarily redirect stderr in a Ruby script for the duration of a block, ensuring that I reset it to its original value at the end of the block.
I had
Essentially the same as @molf's answer, and has the same usage:
require "stringio"
def capture_stderr
real_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
$stderr = real_stderr
end
It uses StringIO very slightly more concisely, and preserves $stderr as whatever it was before capture_stderr was called.