多个文件作为命令行参数?

时间:2014-09-28 20:51:50

标签: ruby

我编写了一个脚本来从文件中读取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)

使用多个文件运行此脚本会出现此错误:

  

文件file1 file2不存在!

它们没有用逗号或任何东西分隔,因此它不会将我的参数读作:[“file1”,“file2”],这是我原来的问题。我不理解的是什么?

1 个答案:

答案 0 :(得分:0)

你写了

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

你为什么这样做? 你正在改变数组.. &#34;文件&#34;数组已经是一个数组,你不必用字符串连接它。

EDIT1: 要获取每次运行的特定文件,您应该写:

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