Sunday, May 16, 2010

Redirecting Console Output: File

If you have occasion to require to redirect some console output produced by your code to a file, you can accomplish this with a few lines of code like so:

  f = File::open('console.log', 'w')
  begin
    temp_std_out = STDOUT.clone
    STDOUT.reopen(f)
    puts 'this will go to the file'
  ensure
    STDOUT.reopen(temp_std_out)
    puts 'this will go to the screen'
  end

No comments: