3

I'm writing a little script in Ruby that removes comments from Ruby files:

#!/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

I am stuck on how to remove these lines that match the regex in the #todo section, it would be great if someone could help!

mtkcs
  • 1,696
  • 14
  • 27

2 Answers2

3

change:

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

to:

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

You would be reading the accepted lines into an array(accepted_content), and writing back that array into the file

bjhaid
  • 9,592
  • 2
  • 37
  • 47
1

I would do this by creating a temporary file:

open('tmp', 'w') do |tmp| 
  File.open(file).each do |line| 
    tmp << line unless line =~ /#(?!\!).+/ 
  end
end
File.rename('tmp', file)
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • This approach makes much more sense if you read the original file line by line using `File.open(file).each do |line|` instead of reading it all in memory using `readlines` and the iterating over the resulting array. – toro2k Mar 12 '14 at 13:11