sawa sawa - 4 months ago 36
Ruby Question

How can I clear a `StringIO` instance?

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.

Answer

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
# => ""