2014-09-28 49 views
0

我寫了一個腳本來從文件中讀取IP地址並在文件中打印數量。我並不完全滿意,所以我試圖修改它以允許讀取多個文件,並且我將通過cmd參數指定文件。我遇到的問題是它似乎將多個文件讀作一個參數。多個文件作爲命令行參數?

def host_count(*files) 

begin 

    files.each do 
     files = files.join(' ') 
     read = IO.read(files) 
     reg = read.scan(/(?:\d{1,3}\.){3}\d{1,3}/).size 

     puts "There are " << reg.to_s << " IP addresses in #{files}." 
    end 

rescue Errno::ENOENT 
    puts "File #{files} does not exist!" 

rescue TypeError 
    puts "Usage: #{$0} [file]" 
    puts "Example: #{$0} /home/user/ipfile.txt" 
end 

end 


host_count(ARGV) 

運行此腳本使用多個文件給我這個錯誤:

File file1 file2 does not exist!

他們不是用逗號或任何分離,所以它不讀我的論點是:「文件1」,「文件2 「],這是我原來的問題。我不瞭解什麼?

回答

0

你寫

files.each do 
    files = files.join(' ') 

你爲什麼要這麼做? 你正在改變數組.. 「文件」數組已經是一個數組,你不必使用字符串加入它。

EDIT1: 獲得每次運行特定文件,你應該寫:

files.each do |file| 
    puts file # will print "file 1", and in the next iteration will print "file 2". 
end 
+0

我得到這個錯誤,如果我刪除:./ipcount.rb:13:in'讀「:可以」 t將數組轉換爲字符串(TypeError)。如果我改變:read = IO.read(files)to:read = IO.read(files.to_s),那麼我得到這個錯誤:./ipcount.rb:13:in'read':No such file or directory - [ [「file1」,「file2」]](Errno :: ENOENT) 這就是爲什麼我最初試圖通過連接刪除逗號。 – user3674736 2014-09-28 21:23:03

+0

你應該執行'files.each do | file | ...' - 然後在塊內部有'file'變量,它將是「file1」,然後是「file 2」。 – 2014-09-30 20:19:57