Ruby解压字符串

6

我需要在Ruby中处理一个经过压缩的字符串(普通Zip格式)。 据说无法使用Ruby-ZipZip-Ruby保存临时文件。

有什么可行的方法可以解压这个字符串吗?

5个回答

8

rubyzip 自版本1.1.0起支持StringIO

require "zip"
# zip is the string with the zipped contents
Zip::InputStream.open(StringIO.new(zip)) do |io|
  while (entry = io.get_next_entry)
    puts "#{entry.name}: '#{io.read}'"
  end
end

2

1

由于Ruby-Zip似乎缺乏读写IO对象的支持,您可以模拟File。

  1. 创建一个名为File的类,在Zip模块下继承StringIO,例如class Zip::File < StringIO
  2. 创建exists?类方法(返回true)
  3. 创建open类方法(将StringIO传递给块)
  4. 存根关闭实例方法(如果需要)
  5. 可能需要更多的虚拟方法

我会尽快检查这个问题! - pex
1
当然,更好的方法是扩展Ruby-Zip库。 - Roman

0

正如@Roman所提到的,rubyzip目前缺乏读写IO对象(包括StringIO.new(s))。建议改用zipruby,像这样:

gem install zipruby

require 'zipruby'

# Given a string in zip format, return a hash where 
# each key is an zip archive entry name and each
# value is the un-zipped contents of the entry
def unzip(zipfile)
  {}.tap do |h|
    Zip::Archive.open_buffer(zipfile) do |archive|
      archive.each {|entry| h[entry.name] = entry.read }
    end
  end
end

-1

zlib库。与StringIO兼容良好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接