Wednesday, October 24, 2012

gzip compression/decompression in Ruby

Recently I did some investigation compression and decompression in gzip format using Ruby. Here I posted my ruby code:
require 'zlib'
require 'stringio'
require 'json'
def gunzip(data)
io = StringIO.new(data, "rb")
gz = Zlib::GzipReader.new(io)
decompressed = gz.read
end
def gzip(string)
wio = StringIO.new("w")
w_gz = Zlib::GzipWriter.new(wio)
w_gz.write(string)
w_gz.close
compressed = wio.string
end
data = (1..100).collect {|i| {"id_#{i}" => "value_#{i}" } }
contents = data.to_json
compressed = gzip(contents)
decompressed = gunzip(compressed)
puts "compressed string:"
puts compressed
puts "decompressed success? #{decompressed == contents}"
puts "uncompressed data size: #{contents.length}"
puts "decompressed data size: #{compressed.length}"
puts "compress ratio: #{compressed.length.to_f / contents.length.to_f}"
view raw gistfile1.rb hosted with ❤ by GitHub

2 comments:

  1. Thanks for posting. I was having trouble decompressing a .gz file stored as a string in memory, your gunzip method helped me figure it out.

    ReplyDelete