# STDOUT to StringIO

**URL:** <https://rubytalk.org/t/stdout-to-stringio/42392>\
**Category:** ruby-talk\
**Created:** [21 November 2007 09:15 UTC](https://rubytalk.org/t/stdout-to-stringio/42392 "2007-11-21T09:15:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fredrik](https://avatars.discourse-cdn.com/v4/letter/f/cab0a1/32.png) [@Fredrik](https://rubytalk.org/u/Fredrik)\
**Post date:** [21 November 2007 09:15 UTC](https://rubytalk.org/t/stdout-to-stringio/42392/1 "2007-11-21T09:15:00Z")

</div>

I know that I can redirect my standard output to a file like this:

STDOUT.reopen(File.open(filename,'w'))

But then, why can't I redirect it to a string like this? :

output = StringIO.open('','w')  
STDOUT.reopen(output)

> TypeError: can't convert StringIO into String

Can somebody see what I am doing wrong?

Thanks a lot!  
Fredrik

---

<div class="post-metadata">

**Author:** ![Ryan\_Davis1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/ryan_davis1/32/1848_2.png) [@Ryan\_Davis1](https://rubytalk.org/u/Ryan_Davis1)\
**Post date:** [21 November 2007 10:18 UTC](https://rubytalk.org/t/stdout-to-stringio/42392/2 "2007-11-21T10:18:20Z")

</div>

> I know that I can redirect my standard output to a file like this:
> 
> STDOUT.reopen(File.open(filename,'w'))
> 
> But then, why can't I redirect it to a string like this? :
> 
> output = StringIO.open('','w')  
> STDOUT.reopen(output)
> 
> > TypeError: can't convert StringIO into String
> 
> Can somebody see what I am doing wrong?

\>\> $stderr = output  
=\> #\<StringIO:0x404e8\>  
\>\> warn "blah"  
=\> nil  
\>\> output.string  
=\> "blah\n"

> **···**
>
> On Nov 21, 2007, at 01:15 , Fredrik wrote:

---

<div class="post-metadata">

**Author:** ![Eric\_Hodel1](https://avatars.discourse-cdn.com/v4/letter/e/a9adbd/32.png) [@Eric\_Hodel1](https://rubytalk.org/u/Eric_Hodel1)\
**Post date:** [21 November 2007 21:09 UTC](https://rubytalk.org/t/stdout-to-stringio/42392/3 "2007-11-21T21:09:54Z")

</div>

Also:

[http://blog.segment7.net/articles/2006/08/17/stdout-vs-stdout](http://blog.segment7.net/articles/2006/08/17/stdout-vs-stdout)

> **···**
>
> On Nov 21, 2007, at 02:18 , Ryan Davis wrote:
> 
> > On Nov 21, 2007, at 01:15 , Fredrik wrote:
> > 
> > > I know that I can redirect my standard output to a file like this:
> > > 
> > > STDOUT.reopen(File.open(filename,'w'))
> > > 
> > > But then, why can't I redirect it to a string like this? :
> > > 
> > > output = StringIO.open('','w')  
> > > STDOUT.reopen(output)
> > > 
> > > > TypeError: can't convert StringIO into String
> > > 
> > > Can somebody see what I am doing wrong?
> > 
> > \>\> $stderr = output  
> > =\> #\<StringIO:0x404e8\>  
> > \>\> warn "blah"  
> > =\> nil  
> > \>\> output.string  
> > =\> "blah\n"
> 
> --  
> Poor workers blame their tools. Good workers build better tools. The  
> best workers get their tools to do the work for them. -- Syndicate Wars
