From: Michael Malone Date: 2009-03-25T05:22:26+09:00 Subject: Re: problem with gsub! in file >> I am new to Ruby and trying to do a find and replace on a text file >> based on a regular expression. When I step through the code line by >> line, it appears that the appropriate line in the file is changed, but >> when I exit the function, the file hasn't been modified. Are in-place >> edits of files allowed? can you see what it wrong here? >> >> Here is the body of the function: >> >> def ReplaceGuid(guid) >> r = nil >> sconfProj = File.open("myfile.vcproj", "r+").each do |line| >> m = @guidExp.match(line) >> if !m.nil? >> str = m[1] >> r = %r{#{str}} >> line.gsub!(r, guid) >> break >> end >> end >> end >> >> Many thanks, >> Jen >> The problem is this: you're reading the contents of your file into memory, changing the copy in memory and expecting it to propagate to the physical file. Try this: (though I haven't tested or run it, so there might be some errors) def ReplaceGuid(guid) outfile = File.new("Some_filename", 'w') found_match = false IO.read("myfile.vcproj").each_line do |line| if (@guidExp =~ (line)) && !found_match line.gsub!($1, guid) found_match = true end outfile.puts line end outfile.close end That reads in the original and writes the output to a new file. I'm assuming you wanted to stop at the first match, which is what would happen in your original code. HTH, Michael ======================================================================= This email, including any attachments, is only for the intended addressee. It is subject to copyright, is confidential and may be the subject of legal or other privilege, none of which is waived or lost by reason of this transmission. If the receiver is not the intended addressee, please accept our apologies, notify us by return, delete all copies and perform no other act on the email. Unfortunately, we cannot warrant that the email has not been altered or corrupted during transmission. =======================================================================