How to decompress Gzip string in ruby?

Fluffy picture Fluffy · Sep 1, 2009 · Viewed 40.3k times · Source

Zlib::GzipReader can take "an IO, or IO-like, object." as it's input, as stated in docs.

Zlib::GzipReader.open('hoge.gz') {|gz|
  print gz.read
}

File.open('hoge.gz') do |f|
  gz = Zlib::GzipReader.new(f)
  print gz.read
  gz.close
end

How should I ungzip a string?

Answer

Garth picture Garth · Sep 2, 2009

The above method didn't work for me.
I kept getting incorrect header check (Zlib::DataError) error. Apparently it assumes you have a header by default, which may not always be the case.

The work around that I implemented was:

require 'zlib'
require 'stringio'
gz = Zlib::GzipReader.new(StringIO.new(resp.body.to_s))    
uncompressed_string = gz.read