On Jul 17, 2006, at 10:31 PM, Xavier Hanin wrote: > Logan Capaldo wrote: >> >> The ! (pronounced bang usually) means that a method is a "dangerous" >> version of a method with the same name. In this particular case it >> means that it's the inplace version of gsub (global substitution). > > OK, thanks for the information and the pronounciation tip. > > But I still don't know how to edit a file while reading it. I've made > further googling on the subject, and the only solutions I find are: > - "read all, manipulate, write all", which doesn't seem very good with > huge files > - use -i options with ruby command line, but this seems to work only > with files passed on the command line, which isn't my case. > > So, could somebody tell me if it's possible to update a file in ruby > (except these two solutions)? > > -- > Posted via http://www.ruby-forum.com/. > To do in place editing, basically you just do it. The problem is doing it correctly. One way is to use fixed-size chunks: CHUNK_SIZE = 1024 File.open("somefile", "r+") do |f| loop do pos = f.tell s = f.read(CHUNK_SIZE) break if s.nil? # We've read and transformed the file s.gsub!(/a/, 'b') f.seek(pos, IO::SEEK_SET) f.write(s) end end The problem with this method is if the substitued string is longer or shorter than the read string it'll mess it up and you'll have to shift the rest of the file around. Another way (and how I believe ruby's command line switch -i works) is to write the modified version to a temporary file, and then remove the original version, replacing it with the modified version. A third, relatively idiot proof method is to use the mmap extension. This is awesome, but is not gonna be portable outside of a *nix. (And introduces another dependency).