How to decompress Gzip string in ruby?

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

You need Zlib::Inflate for decompression of a string and Zlib::Deflate for compression

  def inflate(string)
    zstream = Zlib::Inflate.new
    buf = zstream.inflate(string)
    zstream.finish
    zstream.close
    buf
  end

Zlib by default asumes that your compressed data contains a header. If your data does NOT contain a header it will fail by raising a Zlib::DataError.

You can tell Zlib to assume the data has no header via the following workaround:

def inflate(string)
  zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end

Tags:

Ruby

Zlib

Gzip