Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip a string in memory Ruby

Is there a way to zip a string (either with a gem or standard lib) so that I can get the zipped result of a string? Example:

"hello world".zip #=> zipped version of string

Also, decompression would be nice if someone could include that in their solution.

like image 894
adrian Avatar asked Feb 08 '26 05:02

adrian


2 Answers

You can use Zlib

>> require 'zlib'
=> true
>> s = "this is a long string with many many many many repetition"
=> "this is a long string with many many many many repetition"
>> s.size
=> 57
>> cs = Zlib.deflate(s)
=> "x\x9C+\xC9\xC8,V\x00\xA2D\x85\x9C\xFC\xBCt\x85\xE2\x92\xA2L U\x9EY\x92\xA1\x90\x9B\x98W\x89N\x14\xA5\x16\xA4\x96d\x96d\xE6\xE7\x01\x00\\?\x15P"
>> cs.size
=> 48
>> is = Zlib.inflate(cs)
=> "this is a long string with many many many many repetition"
like image 76
Ismael Avatar answered Feb 14 '26 16:02

Ismael


I'd like to refer you to this nice answer by vas, it details the rubyzip gem, which, as you can see in the documentation has input and outputstream objects and should do exactly what you want.

like image 23
Harald Brinkhof Avatar answered Feb 14 '26 17:02

Harald Brinkhof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!