- Reassigning global $stdout to console - ruby
- test.rb :
- old_stdout = $stdout
- $stdout.reopen("mytestfile.out",'w+')
- puts "this goes in mytestfile"
- $stdout= old_stdout
- 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"
- ruby test.rb => no output on the console
- cat mytestfile.out
- this goes in mytestfile
- this should be on the console
- cat mytestfile1.out
- this goes in mytestfile1:
- this should be back on the console
- 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"
- ruby test.rb
- # => this should be on the console
- # => this should be back on the console
- cat mytestfile.out
- # => this goes in mytestfile
- cat mytestfile1.out
- # => this goes in mytestfile1
- # Runs a block of code while blocking stdout.
- # Note that /dev/null should be changed to NUL on Windows.
- def silence_stdout(log = '/dev/null')
- old = $stdout.dup
- $stdout.reopen(File.new(log, 'w'))
- yield
- $stdout = old
- end
- 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"
- old_stdout = $stdout
- $stdout = File.new("mytestfile.out",'w+')
- puts "this goes in mytestfile"
- $stdout = old_stdout
- puts "this should be on the console"
- $stdout = File.new("mytestfile1.out",'w+')
- puts "this goes in mytestfile1:"
- $stdout = old_stdout
- puts "this should be back on the console"