Ruby 是什么原因导致了;“已初始化常量”;警告
我的代码怎么了?Ruby 是什么原因导致了;“已初始化常量”;警告,ruby,search,dir,Ruby,Search,Dir,我的代码怎么了?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/"
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
number=0
而数字<99
数字=数字+1
如果Ruby变量名中的数字,那么它很重要。局部变量必须以a开头。常量-带大写字母
因此,请尝试将FileNameArray
重命名为FileNameArray
另外,glob
采用高级表达式,可以节省一个循环和十几个LOC。在您的情况下,此表达式应类似于:
Dir.glob(“/home/product/00[0-9][0-9]/*/*.txt”)
您可能是一个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
注意事项:
在ruby中,如果使用前缀为$
符号的变量,则将其视为全局变量。因此,只有在需要时才使用$find
在ruby中,常量变量
以大写字母
开头,通常我们不应该更改常量值。这可能导致程序中出现错误
(1..99)
是用于创建类实例的文本,该类返回1到99之间的值
FileNameArray是一个常量(因为它是大写的),您正在循环中定义它。@AlexD我自己刚开始使用Ruby,关于大写是创建常量的一点点信息非常有用,谢谢!使用Dir.glob(“/home/product/00[0-9][0-9]/*/*/*.txt”)首先循环非常慢,因为Dig.glob将完全扫描直接文件名,而不是将文件名传递给其他进程?您测量过吗?另外,如果那里没有99个文件夹,但是只有20个,那么for循环仍然会调用glob 99次,这是不对的