2017-01-23 91 views
1

我正在寫一個簡單的程序,它接受一個輸入字符串,將其拆分爲單詞並將其保存在內存中。有三種方法 - 將字符串保存到內存中,從文件加載並從zip壓縮文件加載。下面的代碼:ENOENT ENOENT嘗試讀取壓縮文件

require 'zip' 

class Storage 
    def initialize 
    @storage = '' 
    end 

    def add(string) 
    words = string.split ',' 
    words.each do |word| 
     @storage << "#{word}," 
    end 
    end 

    def load_from_file(filename) 
    File.open filename, 'r' do |f| 
     f.each { |line| add line } 
    end 
    end 

    def load_from_zip(filename) 
    Zip::File.open "#{filename}.zip" do |zipfile| 
     zipfile.each { |entry| load_from_file entry.to_s } 
    end 
    end 
end 

雖然addload_from_file方法如我所料很好地工作,load_from_zip每次我嘗試運行它返回我下面的錯誤:雖然在文件中我的檔案存在

storage.rb:39:in `initialize': No such file or directory @ rb_sysopen - test.txt (Errno::ENOENT) 

。我將不勝感激,我做錯了

回答

1
Zip::File.open "#{filename}.zip" 

什麼不提取zip文件的任何建議,它只是打開它,顯示裏面有什麼。 不能調用

File.open filename, 'r' 

因爲filename是不是在你的文件系統,只需將.zip文件內。

你需要添加一個新方法:

require 'zip' 

class Storage 
    def initialize 
    @storage = '' 
    end 

    def add(string) 
    words = string.split ',' 
    words.each do |word| 
     @storage << "#{word}," 
    end 
    end 

    def load_from_file(filename) 
    File.open filename, 'r' do |f| 
     f.each { |line| add line } 
    end 
    end 

    def load_from_zip(filename) 
    Zip::File.open "#{filename}.zip" do |zipfile| 
     zipfile.each { |entry| load_from_zipped_file(zipfile,entry)} 
    end 
    end 

    private 

    def load_from_zipped_file(zipfile, entry) 
    zipfile.read(entry).lines.each do |line| 
     add line 
    end 
    end 
end 

s = Storage.new 
s.load_from_zip('test') 
+0

這是輝煌的,謝謝! – AlexNikolaev94