Recover values from Ruby's StringIO

In Ruby, there is a class called StringIO that creates a string by pretending to write it to a file. It's convenient to use, but I was a little addicted to it.

What is String IO?

First, there is a class called ʻIO that controls reading and writing to files and pipes, moving positions in files, and so on. If the read / write method takes the actual output destination with ʻIO, it can be used regardless of the actual access destination.

On the other hand, StringIO allowsString to be handled by the interface of ʻIO. You can retrieve the value as a string by passing StringIO to a method that takes ʻIO as an argument.

There is no inheritance relationship between StringIO and ʻIO`, and it is implemented as duck typing.

Example of value recovery failure

So I tried to get the value with StringIO, but sometimes it failed.

Failure example


sio = StringIO.new
SomeAPI.download(key, output: sio)
data = sio.read

Since it is ʻIO, I thought that I should do read, but with this, the value that can be taken in data` will be an empty string.

Factors of failure and remedies

Although it is a cause of failure, StringIO also records the current position, so if you repeat the addition and write to StringIO, the position is at the end. Even if you do read as it is, nothing can be taken because it is already at the end.

Of course, you can do rewind and then read, but even if you don't do that, you can use StringIO # string to get the string you have as a buffer.

External link

Recommended Posts

Recover values from Ruby's StringIO