0

So I'm trying to redirect output to a file temporarily:

  prev_std = STDOUT

  $stdout.reopen(@filename, 'w:UTF-8')

  # stuff happens here with @filename and lots of output

  $stdout = prev_std

but when I do this, it seems as though I can't redirect it back afterwards. What am I doing wrong here?

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
Grace B.
  • 49
  • 5

2 Answers2

1

STDOUT is a constant that represents the standard output, which is an IO object. And $stdout is a global variable whose default values is usually STDOUT itself, by default, both point to the same object:

$stdout.object_id == STDOUT.object_id => true

If you call a method on one of them, the other one will be affected. So if you call a method using $stdout it will also take effect on STDOUT. Calling reopen on $stdout will affect STDOUT as well (even if it's a constant).

If you want to redirect output to a file temporarily and restore it then to the standard output, you should assign $stdout a new IO object:

$stdout = File.open('/path/to/file', 'w:UTF-8')
puts "this will go to the file"
$stdout = STDOUT
puts "this will go to standard output!"

See also the following questions:

Community
  • 1
  • 1
Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
0

You're calling reopen on STDOUT since $stdout is just a global variable that points to the same object. This permanently changes STDOUT.

What about this:

$stdout = File.open(@filename, 'w:UTF-8')

# ...

$stdout = prev_std
tadman
  • 208,517
  • 23
  • 234
  • 262