From: Jeremy Bopp Date: 2010-09-19T02:00:33+09:00 Subject: Re: search and replace On 09/18/2010 11:14 AM, John Smith wrote: > Both solutions almost work, only that I want the first instance to be > replaced. > For example > > 1 4 > 1 4 > 1 5 > 1 4 > 1 5 > > one four > 1 4 > 1 5 > 1 4 > 1 5 Alright, so you only want a search/replace pair to apply to a single line in the file to be processed. After the search/replace pair has been applied one time, it should be dropped from the list of pairs to try so that it cannot be used on subsequent lines. Try this: changes = [ ['string1', 'replacement1'], ['string2', 'replacement2'], ... ] File.open('somefile') do |f| f.each do |line| line_changed = false changes.each do |change| if line.sub!(change[0], change[1]) then line_changed = true changes.delete(change) puts line break end end puts line unless line_changed end end -Jeremy