6

In Java, one can create an IO stream from a String like so:

Reader r = new StringReader("my text");

I'd like to be able to do the same in Ruby so I can take a string and treat it as an IO stream.

brianegge
  • 29,240
  • 13
  • 74
  • 99

1 Answers1

12
r = StringIO.new("my text")

And here's the documentation.

fearless_fool
  • 33,645
  • 23
  • 135
  • 217
molf
  • 73,644
  • 13
  • 135
  • 118
  • 1
    One key thing that bit me (it's in the documentation; I just missed it) is that to get the result out you use #string, not #to_s. #to_s just tells you it's a StringIO. #string gives you the built result. – James A. Rosen Jun 09 '09 at 12:13
  • See also http://stackoverflow.com/questions/10323/why-doesnt-ruby-have-a-real-stringbuffer-or-stringio – James A. Rosen Jun 09 '09 at 12:13
  • i'm using this to insert chart data from Gruff into a prawn PDF. – eggie5 May 30 '13 at 00:03