Ruby 检查文件中是否使用了数组元素

Ruby 检查文件中是否使用了数组元素,ruby,arrays,Ruby,Arrays,我有下面的代码试图检查数组元素是否被使用,但没有被使用:请纠正我的错误。我打开myclass.css并遍历每个hline,添加所有以哈希标记或数组中的点开头的选择器,然后拆分数组元素并删除重复项。删除重复项后,我使用此列表检查它们是否在compliated.js文件中使用。如果未使用,我将添加到新数组中 list_selectors = [] file = File.open("myclass.css") file.each_line do |line| list_selectors

我有下面的代码试图检查数组元素是否被使用,但没有被使用:请纠正我的错误。我打开myclass.css并遍历每个hline,添加所有以哈希标记或数组中的点开头的选择器,然后拆分数组元素并删除重复项。删除重复项后,我使用此列表检查它们是否在compliated.js文件中使用。如果未使用,我将添加到新数组中

list_selectors = []
file = File.open("myclass.css") 
file.each_line do |line|
    list_selectors << line.split(' {')[0] if line.start_with? '.' or line.start_with? '#' 
end 
while line = file.gets
    puts line 
end
i = 0 
    while i < list_selectors.length
        puts  "#{list_selectors[i]}"
        i += 1
    end
list = []
list_selectors.each { |x| 
    list.push(x.to_s.split(' ')) 
    }

list_selectors = list.flatten
# puts "***************splitted ******************************"
puts list_selectors
# puts "*********** split before dot ************************"
list_selectors.map! { |e| e[/[.#].*/]}

puts list_selectors

# puts "**************remove duplicates ********************"

list_of_classes_ids = list_selectors.uniq
list_selectors.uniq!
puts list_selectors
# puts "^^^^^^^^^^^^^^^^^not found ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"


for ic in 0..list_of_classes_ids.length
    puts " #{list_of_classes_ids[ic]}"
end

selectors_not_found = []

while nf = File.readlines("compile.js")
    if !list_of_classes_ids[ic]
        selectors_not_found << nf
else
    puts "Exists" 
end
end

puts "////////*********************************////////////////"

puts selectors_not_found
list_选择器=[]
file=file.open(“myclass.css”)
file.u每行do |行|
列出选择器您的问题在这里:

while nf = File.readlines("compile.js")
  if !list_of_classes_ids[ic]
    selectors_not_found << nf
  else
    puts "Exists" 
  end
end
这段代码可能仍然无法工作,因为它不会检查任何合理的内容,但您的代码应该停止因内存问题而出现故障


更新

如果您想要列出compile.js中未出现的
list\u of_classes\u id
中的所有单词,请尝试执行以下操作:

compile_js = IO.read('compile.js')
selectors_not_found = list_of_classes_ids.compact.reject { |class_id| compile_js[class_id] }

那么第44行是哪一行???没关系。这什么时候是假的?虽然nf=File.readlines(“compile.js”)是第44行,而nf=File.readlines(“compile.js”)是对的,而且总是对的,所以把nf塞进选择器会耗尽你的内存。在读了这些行之后,我想检查compile.js中是否存在列表类ID。@user3635322,所以你需要得到一个ic列表(不管是什么)从compiled.js中取出,然后从类的列表中减去。这将使您在compiled.js中保留css中没有的任何ic。如果你用tdd攻击这个问题,你会得到一个更好的设计,并且知道你的bug在哪里。@Uri我试过它说它
[]
:在主拒绝中没有从nil到integer(TypeError)块的隐式转换main@TonyHopkinson我已经从css那里拿到了名单,我需要使用list_classes_id来检查它们是否在compiled.js中使用,如果使用了,我将忽略它们,如果没有使用,我将它们添加到array not found中。@UriAgassi我尝试过它,但我不确定它是否符合我的需要,我会再次测试它,然后告诉我它是否正常工作,并给出正确的结果。谢谢
compile_js = IO.read('compile.js')
selectors_not_found = list_of_classes_ids.compact.reject { |class_id| compile_js[class_id] }