From: "David A. Black" Date: 2009-06-24T02:24:46+09:00 Subject: Re: formatting a listing Hi -- On Wed, 24 Jun 2009, George George wrote: > David A. Black wrote: >> On Tue, 23 Jun 2009, George George wrote: >> >>> whitespace >>> -6.3 >>> 7 >>> >>> Produce an output such that: >>> 1,-3.05,-6.3 >> >> That's a spurious - before the 3, right? >> >>> 2,4,7 >>> 3,5 >>> >>> or >>> 1,-3.05,-6.3 >>> 2,4,7 >>> 3,5,0 >> >> The example that I couldn't quite figure out was the one with input >> like: >> >> 1 2,3 4 >> >> or something like that. Anyway, a simple version (which may not handle >> that case) is: >> >> $/ = "\n\n" # if the input is definitely \n\n delimited >> >> cols = File.open("input.csv") do |fh| >> max = 0 >> fh.map do |s| >> row = s.scan(/\S+/) >> max = [max, row.size].max >> row << "0" until row.size == max >> row >> end >> end >> >> >> David > > Hi David! > Thanks for the reply but the output given by the above code again > only produces a single column instead of multiple columns. instead of > given > 1 > 2 > 3 > white space > 3.05 > 4 > 5 > whitespace > -6.3 > 7 > > Produce an output such that: > 1,-3.05,-6.3 > 2,4,7 > 3,5 Here's my input and output, along with the program: $ cat george.rb $/ = "\n\n" cols = File.open("input.csv") do |fh| max = 0 fh.map do |s| row = s.scan(/\S+/) max = [max, row.size].max row << "0" until row.size == max row end end rows = cols.transpose.map {|row| row.join(",") } puts rows $ cat input.csv 1 2 3 3.05 4 5 -6.3 7 $ ruby george.rb 1,3.05,-6.3 2,4,7 3,5,0 The columns look OK. Note that the $/="\n\n" thing only works if your input is separated by exactly that sequence. That might be the problem you're having. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com