From: Chris Hulan Date: 2009-03-07T13:38:26+09:00 Subject: Re: text processing On Mar 6, 9:38 pm, Ruby Kk wrote: > Hi there, > I am new to ruby and trying to create a flat file with fixed column > length. i have a header,footer and records that i want in the file. > > any ideas? > > Cheers! > > > > Gary Wright wrote: > > On Mar 30, 2007, at 3:31 PM, Stephen Smith wrote: > >> {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(',') > > } > > -- > Posted viahttp://www.ruby-forum.com/. sprintf allows you specify formatting that can be used to print fixed width. An example from the docs (ruby-doc.org) is: sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'" Note how the %4s puts 3 characters in a space 4 characters wide. cheers