From: Stephen Smith <4fires@...> Date: 2007-03-31T05:39:46+09:00 Subject: Re: text processing ------=_Part_88984_20580150.1175287183972 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Gary, Thanks for the tip. I love the native pattern matching. I had no idea regular expressions could be such powerful objects. And I can't think of a good reason not to use Ruby around the house from now on. I'm going to sit down with a book tonight. And I killed the internal array, btw. I didn't know Ruby iterates through files as easily as arrays. This is like going back to school. Grinning, Steve On 3/30/07, Gary Wright wrote: > > > On Mar 30, 2007, at 3:31 PM, Stephen Smith wrote: > > line = "" > > record = "" > > oldLog = File.open("filename.txt") > > newLog = File.new("filename_formatted.csv", "w") > > hdr = "field1, field2, field3,...." > > newLog << hdr > > arr = oldLog.readlines > > arr.each do |line| > > record << > > /(.{8})(.{6})(.{15})(.{3})(.{30})(.{4})(.{15})(.{1})(.{12})(. > > {9})/.match(line).captures.join(',') > > << "\n" > > newLogg << record > > record = "" > > end > > How about making it so you don't have to type that pattern next time: > > def columns(*widths) > Regexp.new(widths.map {|count| "(.{#{count}})" }.join) > end > pattern = columns(6,15,3,30,4,15,1,12,9) > > You also can get rid of the intermediate strings and the potentially > huge > internal array (from slurping up your oldLog into an array): > > oldLog.each { |line| > newLog.print pattern.match(line).captures.join(',') > } > > ------=_Part_88984_20580150.1175287183972--