我的代码出了什么问题? 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
答案 0 :(得分:5)
你可能是一个红宝石初学者,我试图用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
注意事项,
$
符号前缀的变量,则在ruby中,它将被视为global variable
。因此,只有在需要时才使用$find
。constant variable
以capital letter
开头,通常我们 NOT 应该更改常量值。这可能会导致程序出错。(1..99)
是用于创建Range类实例的文字,它返回1到99之间的值答案 1 :(得分:3)
在Ruby变量名称案例中。局部变量必须以lower case character开头。常量 - 大写。
因此,请尝试将FileNameArray
重命名为fileNameArray
。
此外,glob
采用高级表达式,可以为您节省一个循环和十几个LOC。在您的情况下,此表达式应如下所示:
Dir.glob("/home/product/00[0-9][0-9]/*/*.txt")