从Ruby中的zip中提取单个文件

时间:2013-06-05 23:49:03

标签: ruby zip archive

我需要从zip存档中提取单个文件。以下工作在一点,然后停止。我已经尝试过以最基本的方式从头开始写几次,但它仍然无法找到我正在搜索的文件。

def restore(file)
    #pulls specified file from last commit
    found = []
    #files.each do |file|
        print "Restoring #{file}"
        puts
        Zip::ZipFile.open(".fuzz/commits/#{last_commit}.zip") do |zip_file|
            zip_file.each do |f|

                if f == file.strip
                    if File.exists?(file)
                        FileUtils.mv(file, "#{file}.temp")
                    end

                    FileUtils.cp(f, Dir.pwd)
                    found << file

                    if File.exists?("#{file}.temp")
                        FileUtils.rm_rf("#{file}.temp")
                    end
                else
                    puts "#{file} is not #{f}" #added this to make sure that 'file' was being read correctly and matched correctly.
                end
            end
        end
        print "\r"
        if found.empty? == false
            puts "#{found} restored."
        else
            puts "No files were restored"
        end

    #end
end

“#{file}不是#{f}显示这两个文件,但仍然认为没有匹配。过去的一天我已经抓住了我的大脑。我希望我刚走了愚蠢,我错过了一个明显的缺陷/错字。

2 个答案:

答案 0 :(得分:1)

您引用的链接作为示例有一个很大的区别:

不是f ==而是"#{f}"==。这基本上是一种说f.to_s的神秘方式,这意味着f不是字符串,但是它的to_s方法返回文件的名称。所以,试着替换它:

if f == file.strip

有了这个:

if f.to_s == file.strip

答案 1 :(得分:1)

我尝试了一些实验,发现f == file.strip不起作用:

但是,这两个都有效:

if f.name == file.strip

if f.to_s == file.strip

我个人更喜欢f.name因为它使代码更容易阅读和理解。

相关问题