From: James Dinkel Date: 2009-04-30T23:41:26+09:00 Subject: Re: Read and re-write file with one open? Gregory Brown wrote: > > Here's an example from my upcoming book "Ruby Best Practices"[0]. It > naively strips comments from source files. > You can modify it to fit your needs. > > ---------- > > require "tempfile" > require "fileutils" > > temp = Tempfile.new("without_comments") > File.foreach(ARGV[0]) do |line| > temp << line unless line =~ /^\s*#/ > end > temp.close > > FileUtils.cp(ARGV[0],"#{ARGV[0]}.bak") # comment out if you don't want > backups. > FileUtils.mv(temp.path,ARGV[0]) > > ---------- > > -greg What about if another program opens the file after it has been read by the Ruby program but before the Ruby program has copied the temp file? If the second program makes a change and saves it, those changes will be lost when the Ruby program copies the temp file over it. Or if the second program still has it open and the Ruby program finishes, then when the second program saves it's open file, it will overwrite the Ruby program's changes. -- Posted via http://www.ruby-forum.com/.