# How to Compress a String in Ruby (and Rails)

*Published on September 28, 2022*

---


Ruby's standard library provides the&nbsp;`Zlib`&nbsp;module, which allows you to access the popular&nbsp;[zlib](https://zlib.net/)&nbsp;library, a portable, free, and lossless data-compression library. It performs the compression and decompression functions in memory.

Using&nbsp;`Zlib`&nbsp;module, You can compress a string as follows.

```ruby
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&nbsp;`Inflate`&nbsp;class provided by this module.

```ruby
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&nbsp;`ActiveSupport::Gzip`&nbsp;wrapper, which simplifies the compression API.

```ruby
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&nbsp;`compress`&nbsp;method uses the&nbsp;`Zlib::GzipWriter`&nbsp;class which writes gzipped files. Similarly, the&nbsp;`decompress`&nbsp;method uses&nbsp;`Zlib::GzipReader`&nbsp;class which reads a gzipped file.

