Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes the "already initialized constant" warning?

Tags:

search

ruby

dir

What's wrong with my code? Is FileNameArray being reused?

f.rb:17: warning: already initialized constant 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
like image 869
Acc Avatar asked Feb 21 '23 12:02

Acc


1 Answers

You might be a ruby beginner, I tried to rewrite the same code in ruby way...

(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

Points to note down,

  1. In ruby if you use a variable prefixed with $ symbol, it is taken as a global variable. So use $find, only if it is required.
  2. In ruby a constant variable starts with capital letter, usually we are NOT supposed to change a constant value. This might have caused the error in your program.
  3. (1..99) is a literal used to create instance of Range class, which returns values from 1 to 99
like image 127
nkm Avatar answered Mar 04 '23 00:03

nkm