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

在Ruby中从zip中提取单个文件,ruby,zip,archive,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(".f

我需要从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
def还原(文件)
#从上次提交中提取指定的文件
找到=[]
#文件。每个do |文件|
打印“正在还原#{file}”
放
Zip::ZipFile.open(“.fuzz/commits/#{last_commit}.Zip”)do|Zip|u文件|
zip|u file.each do|f|
如果f==file.strip
如果File.exists?(文件)
mv(文件“#{file}.temp”)
结束
cp(f,Dir.pwd)

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

它不是
f==
,而是
“#{f}”==
。这基本上是说
f.to_s
的一种隐晦方式,意思是
f
不是字符串,而是to_s方法返回文件名。因此,请尝试替换此:

if f == file.strip
为此:

if f.to_s == file.strip

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

然而,这两项工作:

if f.name == file.strip

if f.to_s == file.strip

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

如果f==file.strip
永远不会生成True,那么它看起来像
。尝试添加调试打印,如
put“#{f}”;将“#{file.strip}”
放在
if
前面。是的,我已经这样做了,它显示了两个文件的相同文件名。只是再次尝试了双重检查,但仍然没有找到匹配项。顺便说一句,ZipFile类没有方法
each
@Linuxios,不确定您的第一条评论是什么意思,我从[link]建模,它使用
each
method@Nicholas:看我的答案。所以你和@Sergey Bolgov都解决了!谢谢大家!我建议您使用
f.name
。我更清楚地表达了你的意图。