From: Suraj Kurapati Date: 2008-05-14T07:08:00+09:00 Subject: Re: Switch Two Lines in a File Dana Merrick wrote: > I'm providing two regexes, and the > script is to replace a line that matches one regex with a line that > matches the other. Here's my solution; thanks for the fun exercise. $ cat foo line three line two line one another one another three $ ruby -v switch.rb foo ruby 1.8.6 (2007-09-24 patchlevel 111) [i686-linux] line one line two line three another three another one $ cat switch.rb firstQuery = /one/ secondQuery = /three/ # determine line numbers of matching lines firstIndices = [] secondIndices = [] lines = ARGF.readlines lines.each_with_index do |line, i| case line when firstQuery firstIndices << i when secondQuery secondIndices << i end end # swap all matching lines firstIndices.zip(secondIndices).each do |(a, b)| lines[a], lines[b] = lines[b], lines[a] end puts lines -- Posted via http://www.ruby-forum.com/.