Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 30th, 2012  |  syntax: None  |  size: 1.80 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Reassigning global $stdout to console - ruby
  2. test.rb :
  3.    old_stdout = $stdout    
  4.     $stdout.reopen("mytestfile.out",'w+')
  5.        puts "this goes in mytestfile"
  6.     $stdout= old_stdout
  7. puts "this should be on the console"
  8.     $stdout.reopen("mytestfile1.out",'w+')
  9.        puts "this goes in mytestfile1:"
  10.     $stdout = old_stdout
  11.  puts "this should be back on the console"
  12.        
  13. ruby test.rb => no output on the console
  14. cat mytestfile.out
  15.   this goes in mytestfile
  16.   this should be on the console
  17. cat  mytestfile1.out
  18.   this goes in mytestfile1:
  19.   this should be back on the console
  20.        
  21. old_stdout = $stdout.dup  
  22. $stdout.reopen("mytestfile.out",'w+')
  23. puts "this goes in mytestfile"
  24. $stdout = old_stdout.dup
  25. puts "this should be on the console"
  26. $stdout.reopen("mytestfile1.out",'w+')
  27. puts "this goes in mytestfile1:"
  28. $stdout = old_stdout
  29. puts "this should be back on the console"
  30.        
  31. ruby test.rb
  32. # => this should be on the console
  33. # => this should be back on the console
  34. cat mytestfile.out
  35. # => this goes in mytestfile
  36. cat mytestfile1.out
  37. # => this goes in mytestfile1
  38.        
  39. # Runs a block of code while blocking stdout.
  40. # Note that /dev/null should be changed to NUL on Windows.
  41. def silence_stdout(log = '/dev/null')
  42.   old = $stdout.dup
  43.   $stdout.reopen(File.new(log, 'w'))
  44.   yield
  45.   $stdout = old
  46. end
  47.        
  48. silence_stdout 'mytestfile.out' do
  49.   puts "this goes in mytestfile"
  50. end
  51.  
  52. puts "this should be on the console"
  53.  
  54. silence_stdout 'mytestfile1.out' do
  55.   puts "this goes in mytestfile1"
  56. end
  57.  
  58. puts "this should be back on the console"
  59.        
  60. old_stdout = $stdout    
  61. $stdout = File.new("mytestfile.out",'w+')
  62. puts "this goes in mytestfile"
  63. $stdout = old_stdout
  64. puts "this should be on the console"
  65. $stdout = File.new("mytestfile1.out",'w+')
  66. puts "this goes in mytestfile1:"
  67. $stdout = old_stdout
  68. puts "this should be back on the console"