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.
StringIO. close() is merely a convenience for routines that take a file-like and eventually attempt to close them. There is no need to do so yourself. It's not a convenience, rather a necessity.
The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
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
# => ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With