Michal Suchanek
2/9/2009 10:53:00 AM
2009/2/8 7stud -- <bbxx789_05ss@yahoo.com>:
> In pickaxe2, on p. 335, it says that assigning to $stdout is deprecated
> and to use $stdout.reopen() instead:
>
> -------------------------------------------------------------- IO#reopen
> ios.reopen(other_IO) => ios
> ios.reopen(path, mode_str) => ios
> ------------------------------------------------------------------------
> Reassociates _ios_ with the I/O stream given in _other_IO_ or to a
> new stream opened on _path_. This may dynamically change the actual
> class of this stream.
>
> f1 = File.new("testfile")
> f2 = File.new("testfile")
> f2.readlines[0] #=> "This is line one\n"
> f2.reopen(f1) #=> #<File:testfile>
> f2.readlines[0] #=> "This is line one\n"
>
>
> And there is this in the Standard LIbrary:
>
> StringIO
>
> Once a string is wrapped in a StringIO object, it can be read from and
> written to as if it were an open file....It also lets you pass strings
> into classes and methods that were originally written to work with
> files.
>
> But I get an error trying to replace $stdout with a StringIO object:
>
> require "stringio"
>
> strio = StringIO.new
> old_out = $stdout
> $stdout.reopen(strio)
>
> --output:--
> r1test.rb:5:in `reopen': cannot convert StringIO into String (TypeError)
> from r1test.rb:5
>
> What am I doing wrong?
Not reading the docs.
It should be obvious from description of IO#reopen that you cannot use
StringIO in this way because it does not have an underlying file
descriptor.
On the other hand, you can assign a StrinIO into $stdout but this will
change only the global, not the file descriptors seen by C extensions
or programs executed with system().
HTH
Michal