Search code examples
rubyio

How can I convert an IO object to a string in Ruby?


I'm working with an IO object (some STDOUT output text), and I'm trying to convert it to a string so that I can do some text processing. I would like to do something like this:

my_io_object = $stdout
#=> #<IO:<STDOUT>>

my_io_object.puts('hi')  #note: I know how to make 'hi' into a string, but this is a simplified example
#=>hi

my_io_object.to_s

I have tried a few things and gotten a few errors:

my_io_object.read 
#=> IOError: not opened for reading

my_io_object.open
#=> NoMethodError: private method `open' called for #<IO:<STDOUT>>

IO.read(my_io_object)
#=> TypeError: can't convert IO into String

I've read through the IO class methods, and I can't figure out how to manipulate the data in that object. Any suggestions?


Solution

  • I solved this by directing my output to a StringIO object instead of STDOUT:

    > output = StringIO.new
    #<StringIO:0x007fcb28629030>
    > output.puts('hi')
    nil
    > output.string
    "hi\n"