6

How can I clear a StringIO instance? After I write to and read from a string io, I want to clear it.

require "stringio"
io = StringIO.new
io.write("foo")
io.string #=> "foo"
# ... After doing something ...
io.string #=> Expecting ""

I tried flush and rewind, but I still get the same content.

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

6

seek or rewind only affect next read/write operations, not the content of the internal storage.

You can use StringIO#truncate like File#truncate:

require 'stringio'
io = StringIO.new
io.write("foo")
io.string
# => "foo"
io.truncate(0)   # <---------
io.string
# => ""

Alternative:

You can also use StringIO#reopen (NOTE: File does not have reopen method):

io.reopen("")
io.string
# => ""
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 2
    It appears that [StringIO#reopen](http://ruby-doc.org/stdlib-1.9.3/libdoc/stringio/rdoc/StringIO.html#method-i-reopen) works as well: `io.string #=> "foo"; io.reopen(''); io.string #=> ""` . Yes? – Cary Swoveland Feb 11 '15 at 01:44
  • @CarySwoveland, Thank you for the comment. I didn't know it. I updated the answer accordingly. – falsetru Feb 11 '15 at 01:51
  • Please see the answer below by JML. Without the rewind, future writes to the StringIO will begin at the position after the length of the previous value, and the string will be left padded with binary zeros. – Keith Bennett Feb 11 '22 at 12:57
4

I use truncate AND rewind. The rewind is required to prepare io for next operations.

io.truncate(0)
io.rewind
Jesus Monzon Legido
  • 1,253
  • 12
  • 10