Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

12.10. Compressing and Archiving Files with Gzip and Tar

Problem

You want to write compressed data to a file to save space, or uncompress the contents of a compressed file. If you're compressing data, you might want to compress multiple files into a single archive file.

Solution

The most common compression format on Unix systems is gzip. Ruby's zlib library lets you read to and write from gzipped I/O streams as though they were normal files. The most useful classes in this library are GzipWriter and GzipReader.[3]

Here's GzipWriter being used to create a compressed file, and GzipReader decompressing the same file:

	require ' 
zlib'

	file = 'compressed.gz'
	Zlib::GzipWriter.open(file) do |gzip|
	  gzip << "For my next trick, I'll be written to a compressed file."
	  gzip.close
	end

	open(file, 'rb') { |f| f.read(10) }
	# => "\037\213\010\000\201\2766D\000\003"

	Zlib::GzipReader.open(file) { |gzip| gzip.read }
	# => "For my next trick, I'll be written to a compressed file."

Discussion

GzipWriter and GzipReader are most commonly used to write to files on disk, but you can wrap any file-like object in the appropriate class and automatically compress everything you write to it, or decompress everything you read from it.

The following code works the same way as the compression code in the Solution, but it's more flexible: the File object that's passed into the Zlib::GzipWriter constructor could just as easily be a Socket or other file-like object.

 open('compressed.gz', 'wb') do |file| gzip = Zlib::GzipWriter.new(file) ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required