Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear a `StringIO` instance?

Tags:

ruby

stringio

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.

like image 480
sawa Avatar asked Feb 11 '15 01:02

sawa


People also ask

Do I need to close StringIO Python?

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.

What is StringIO StringIO?

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.

What is BytesIO Python?

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.


1 Answers

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
# => ""
like image 103
falsetru Avatar answered Oct 08 '22 15:10

falsetru