This problem can be solved by calling dup on $stdoutbefore changing it:
old_stdout = $stdout.dup
$stdout.reopen("mytestfile.out",'w+')
puts "this goes in mytestfile"
$stdout = old_stdout.dup
puts "this should be on the console"
$stdout.reopen("mytestfile1.out",'w+')
puts "this goes in mytestfile1:"
$stdout = old_stdout
puts "this should be back on the console"
Conclusion:
ruby test.rb
cat mytestfile.out
cat mytestfile1.out
This is how I usually set this function to a function:
def silence_stdout(log = '/dev/null')
old = $stdout.dup
$stdout.reopen(File.new(log, 'w'))
yield
$stdout = old
end
Using:
silence_stdout 'mytestfile.out' do
puts "this goes in mytestfile"
end
puts "this should be on the console"
silence_stdout 'mytestfile1.out' do
puts "this goes in mytestfile1"
end
puts "this should be back on the console"
Edit: as another poster mentioned, using reopening is only necessary when working with pure Ruby code. The function above works both with pure Ruby code, and when using, for example, C-extensions that are written to STDOUT.
source
share