Skip to content

Instantly share code, notes, and snippets.

@stevez
Created October 24, 2012 13:45
Show Gist options
  • Save stevez/3946134 to your computer and use it in GitHub Desktop.
Save stevez/3946134 to your computer and use it in GitHub Desktop.
gzip_ruby
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}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment