Ruby's standard library provides the Zlib
module, which allows you to access the popular zlib library, a portable, free, and lossless data-compression library. It performs the compression and decompression functions in memory.
Using Zlib
module, You can compress a string as follows.
require 'zlib'
log_file = File.read('log/development.log')
puts log_file.size # 4864196
compressed_log = Zlib::Deflate.deflate(log_file)
compressed_log.size # 283024
As you can see, the compressed file is only 1/5th of the original file.
To decompress a compressed file, use the Inflate
class provided by this module.
original_log = Zlib::Inflate.inflate(compressed_log)
puts original_log.size # 4871532
So that's how you can compress and decompress strings in Ruby.
Compression in Rails
If you are working in a Rails application, you can use the ActiveSupport::Gzip
wrapper, which simplifies the compression API.
compressed_log = ActiveSupport::Gzip.compress('large string')
=> "\x1F\x8B\b\x00yq5c\x00\x03..."
original_log = ActiveSupport::Gzip.decompress(compressed_log)
=> "large string"
Behind the scenes, the compress
method uses the Zlib::GzipWriter
class which writes gzipped files. Similarly, the decompress
method uses Zlib::GzipReader
class which reads a gzipped file.