Looking for a way to compress text (strings, not files) using Crystal Lang : having problem with the reverse operation

56 Views Asked by At

Compressing strings in RAM can be done by

require "compress/gzip"

compressed_string = String.build do |io|
  Compress::Gzip::Writer.open(io) do |gzip|
    gzip << "Compress me"
  end
end

p compressed_string

So far, so good, so I was trying to figure out how to carry out the reverse transform, but the obvious mirror code doesn't seem to be the answer:

#########
# buggy #
#########

decompressed_string = String.build do |io|
  Compress::Gzip::Reader.open(io) do |gzip|
    gzip << compressed_string
  end
end

p decompressed_string
1

There are 1 best solutions below

0
Serge Hulne On

The correct formulation was:


# Compress
compressed_string = String.build do |io|
  Compress::Gzip::Writer.open(io) do |gzip|
    gzip << "Compress me"
  end
end

p compressed_string


# Decompress
str = Compress::Gzip::Reader.open(IO::Memory.new (compressed_string)) do |gzip|
  gzip.gets_to_end
end

p str