From: John Smith Date: 2010-09-18T09:51:14+09:00 Subject: Re: search and replace That one almost works but it needs to do the replacement only the first occurrence. What's the easiest way to fix it to do that. I'm thinking of a 'detect' but I'm not sure where I'd put it. Jeremy Bopp wrote: > On 9/17/2010 2:02 PM, John Smith wrote: >> Hi everyone, >> >> I want to be able to run a program that will do a bunch >> of searches specified in an array of strings, and replace the >> first occurrence of those strings with strings specified on a >> second array for a given text file. >> >> What would be the best way to do this? > > Maybe something like this: > > changes = [ > ['string1', 'replacement1'], > ['string2', 'replacement2'], > ... > ] > > File.open('somefile') do |f| > f.each do |line| > line_changed = false > changes.each do |search, replacement| > if line.sub!(search, replacement) then > line_changed = true > puts line > break > end > end > puts line unless line_changed > end > end > > > -Jeremy -- Posted via http://www.ruby-forum.com/.