4

我的代码有什么问题?是否FileNameArray被重复使用?

f.rb:17:警告:已初始化常量 FileNameArray

number = 0
while number < 99
  number = number + 1
  if number <= 9
    numbers = "000" + number.to_s
  elsif
    numbers = "00" + number.to_s
  end
  files = Dir.glob("/home/product/" + numbers + "/*/*.txt")
    files.each do |file_name|
    File.open(file_name,"r:utf-8").each do | txt |
      if txt =~ /http:\/\//
        if txt =~ /static.abc.com/ or txt =~ /static0[1-9].abc.com/
        elsif
        $find = txt
        FileNameArray = file_name.split('/')
        f = File.open("error.txt", 'a+')
        f.puts FileNameArray[8], txt , "\n"
        f.close
        end
      end
    end
  end
end
4

2 回答 2

5

你可能是一个 ruby​​ 初学者,我尝试用 ruby​​ 方式重写相同的代码......

(1..99).each do |number|
  Dir.glob("/home/product/" + ("%04d" % numbers) + "/*/*.txt").each do |file_name|
    File.open(file_name,"r:utf-8").each do | txt |
      next unless txt =~ /http:\/\//
      next if txt =~ /static.abc.com/ || txt =~ /static0[1-9].abc.com/        

      $find = txt
      file_name_array = file_name.split('/')
      f = File.open("error.txt", 'a+')
      f.puts file_name_array[8], txt , "\n"
      f.close      
    end
  end
end

需要注意的地方,

  1. 在 ruby​​ 中,如果您使用以$符号为前缀的变量,则将其视为global variable. 因此$find,仅在需要时使用。
  2. 在 ruby​​ aconstant variable中以 开头capital letter,通常我们应该改变一个常数值。这可能会导致您的程序出现错误。
  3. (1..99)是用于创建Range类实例的字面量,它返回 1 到 99 之间的值
于 2012-02-13T10:44:17.290 回答
3

在 Ruby 变量名中,大小写很重要。局部变量必须以小写字符开头。常量 - 大写。

所以,请尝试重命名FileNameArrayfileNameArray.

此外,glob采用高级表达式可以为您节省一个循环和十几个 LOC。在您的情况下,此表达式应类似于:

Dir.glob("/home/product/00[0-9][0-9]/*/*.txt")

于 2012-02-13T09:15:44.980 回答