From: zdennis Date: 2005-12-02T04:07:42+09:00 Subject: Re: What is the best way to edit a file to eliminate a line Steve [RubyTalk] wrote: > zdennis wrote: > >> Hope this works better... > > It will still permanently and irrecoverably loose data if the process > terminates (e.g. a process hard-limit is exceeded, an administrator > kills the process explicitly; or an old-fashioned power-cut etc.) just > after starting to write the updated file... so I wouldn't consider it > sufficiently robust for my purposes. > You could modify for your needs: require 'fileutils' class File def self.modify filename if block_given? data = IO.read filename FileUtils.mv filename, "#{filename}.orig" begin file = File.open filename, 'w' yield file, data ensure file.close unless file.closed? end end end end File.modify( 'stuff.txt' ) do |writable_file, original_file_contents| writable_file.write original_file_contents.gsub( /foo(\n|$)/, '' ) end Zach