2014-09-28 51 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