当它与正则表达式匹配时从Ruby文件中删除一个字符串

时间:2014-03-12 12:33:24

标签: ruby regex file

我正在Ruby中编写一个小脚本来删除Ruby文件中的注释:

#!/usr/bin/ruby

def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /(^\s*#|^\t*#)(?!\!).*/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end


puts "Fetching all files in current directory and uncommenting them"
# fetching all  files
files = Dir.glob("**/**.rb")
# parsing each file
files.each do |file|


  #fetching each line of the current file
  uncomment file

end

我坚持如何删除与#todo部分中的正则表达式相匹配的这些行,如果有人可以提供帮助,那就太棒了!

2 个答案:

答案 0 :(得分:3)

变化:

def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /#(?!\!).+/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end

为:

def uncomment(file)
  accepted_content = File.readlines(file).reject { |line| line =~ /#(?!\!).+/ }
  File.open(file, "w") { |f| accepted_content.each { |line| f.puts line } }
end

您将接受的行读入数组(accepted_content),并将该数组写回文件

答案 1 :(得分:1)

我会通过创建一个临时文件来执行此操作:

open('tmp', 'w') do |tmp| 
  File.open(file).each do |line| 
    tmp << line unless line =~ /#(?!\!).+/ 
  end
end
File.rename('tmp', file)