0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

StringIOとGzipWriterを組み合わせるときのIOError対策

Posted at

以下のコードはIOErrorを引き起こします。

sio = StringIO.new
Zlib::GzipWriter.wrap(sio) do |gz|
  gz.puts("hoge")
end

sio.rewind
sio.read
# => IOError: not opened for reading (IOError)

これはGzipWriter#wrapのブロックを抜けるときにGzWriter#closeメソッドが呼ばれ、そのメソッド内でStringIOもcloseするからです。

既にclose済みのStringIOに対するreadはできないので、以下のように新たなStringIOオブジェクトを作成すると良いです。

sio = StringIO.new
Zlib::GzipWriter.wrap(sio) do |gz|
  gz.puts("hoge")
end

new_sio = StringIO.new(sio)
new_sio.read
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?