From: Robert Klemme Date: 2005-04-18T19:39:32+09:00 Subject: Re: Modifying content in a file "Ghislain Mary" schrieb im Newsbeitrag news:4263856D.3050008@lunacymaze.org... > Hi all, > > I've written a little code that replaces some content in a file, but I > really think there is a better way to do so. Here's my code: > > def clean_file(filename) > # Define the new caption > caption = "caption: new caption" > > # Process the content of the file > File.open(filename) do |from_file| > File.open(filename + ".new", 'w') do |to_file| > from_file.each do |line| > case > when line =~ /^caption:.*$/: line.sub!($&, caption) > end > to_file.print line You can do that easier: to_file.puts( /^caption:/ =~ line ? caption : line ) > end > end > end > > # Rename the file > File.delete(filename) > File.rename(filename + ".new", filename) > end > > Can't it be done using the read-write mode on the file? Any better > proposition is welcome ;) Depends on your file's sizes. If they are moderately sized you can slurp the whole thing in, modify contents in mem with a single gsub and then write them in one go. Regards robert