From: Max Ischenko Date: 2001-03-02T23:40:02+09:00 Subject: [ruby-talk:11898] Re: rewrite with Ruby At Fri, 2 Mar 2001 21:45:48 +0900 Hugh Sasse Staff Elec Eng wrote: > On Fri, 2 Mar 2001, Max Ischenko wrote: >> I have the following Ruby code: >> >> def Mutt.afterConfigure >> system("perl -i -p -e 's/^#define DEBUG/#undef DEBUG/' config.h") > [...] >> >> Now, I want to write a generic function that will make changes to a file, > How would one make it really generic? Ruby has -i as well, so how can one > get at it to do: > ruby -i.bak -p -e 'gsub(/^#define DEBUG/, "#undef DEBUG/") config.h > in an elegant way, within a program? Is it worth raising an RCR for open > and IO to have some means to provide this backup facility? I end up with this: patchFile('/tmp/config.h', { 'ICONV' => 'iconv', '#define (DEBUG|USE_DOTLOCK)' => nil, }) def patchFile(fname, subs) if not FileTest.exist? fname or not FileTest.readable? fname not FileTest.writable? fname raise "Can't patch file #{fname}" end lines = IO.readlines(fname) aFile = File.open(fname, 'w') lines.each {|x| line = x subs.each {|key,val| next unless x =~ key if not val puts "Delete line #{x}" line = nil else line = x.gsub(key, val) puts "Change line #{x} to #{line}" end break } aFile.print line if line } aFile.close end PS: I have another version, which accept block as argument, but it seems to be too complex. -- programming, /n./: The art of debugging a blank sheet of paper.