5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Ruby】Zlibを使用して文字列を圧縮・展開する

Posted at

事前準備

特に必要なし。

サンプルコード

# frozen_string_literal: true

require 'zlib'

# 圧縮前の文字列
str = 'Hello World' * 10_000

# 圧縮レベルを指定
# level = Zlib::NO_COMPRESSION # 圧縮しない
# level = Zlib::BEST_SPEED     # 速度優先で圧縮率は低い
level = Zlib::BEST_COMPRESSION # 圧縮率優先で速度は遅い

# 圧縮
deflated_str = Zlib::Deflate.deflate(str, level)

# 展開
inflated_str = Zlib::Inflate.inflate(deflated_str)

puts str.bytesize          # => 110000
puts deflated_str.bytesize # => 252
puts inflated_str.bytesize # => 110000

puts str == inflated_str # => true

参考

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?