Search code examples
rubyzlibunzip

How do I inflate and read zip files using zlib?


How do you unzip a file, or read the contents of a zip file in order to select what to extract?

The .pencast is zip compressed, so I can use the following in bash:

unzip -j *.pencast "*.aac"

But in Ruby:

require 'zlib'

afile = "/Users/name/Desktop/Somepencast.pencast"
puts afile

def inflate(string)
  zstream = Zlib::Inflate.new
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end

inflate(afile)

results in:

/Users/name/Desktop/Somepencast.pencast
prog1.rb:11:in `inflate': incorrect header check (Zlib::DataError)
  from prog1.rb:11:in `inflate'
  from prog1.rb:17

Solution

  • This might help: How do I get a zipped file's content using the rubyzip library?

    zip and gzip are different protocols and need different unzipping software.

    Personally I find rubyzip a bit of a pain to use, so I would be inclined to consider just shelling out to the unzip command you're already using. You can do that with

    `unzip -j *.pencast "*.aac"` # note backticks
    

    or

    system( 'unzip -j *.pencast "*.aac"' )
    

    (or various other ways)