From: pjb@... (Pascal J. Bourguignon) Date: 2009-06-19T20:35:05+09:00 Subject: Re: formatting a listing George George writes: > Thanks a lot Pascal! The code is working though a little complex but a > very nice learning piece of code. one nitty gritty thing is that not all > the columns are seperated by a comma. for example your code > > File.open("/home/george/test_r.csv",'w') do |f| > printf "%s\n\n", > begin > matrix = Array.new > ncols = 1 > matrix.push(Array.new) > (IO.readlines '/home/george/test.data'). > map { | line | (line.strip) }. > each { | item | if item == "" > ncols = (ncols + 1) > matrix.push(Array.new) > else > matrix.at(ncols - 1).push item > end > } > > height = (matrix.map { | column | (column.size) }).max > > widths = matrix.map { | column | ((column.map { | cell | > ((sprintf("%s" , cell)).size) }).max) } > > f.puts((matrix.map { | column | (column + (Array.new((height - > column.size) , ""))) }).transpose. > map { | row | ((([ row , widths ].transpose). > map { | r , w | (sprintf( "%*s" , w , r)) }).join ",")}.join "\n") > end > end > > when given a file(test.data) containing > 1 2 > 2 4 > > 1 4 > 2 3 > > 1 3 > 2 3 > 3 5 > 4 6 > > it produces (test_r.csv) > > 1 2,1 4,1 3 > 2 4,2 3,2 3 > , ,3 5 > , ,4 6 > > which is almost there! > the ideal output would have been > > 1, 2,1, 4,1, 3 > 2, 4,2, 3,2, 3 > , , ,3, 5 > , , ,4, 6 > > Sorry am asking for a horse and the saddle :) what little modification > should i do to produce the second output? You could add a split and a each somewhere. irb(main):001:0> "1 2".split(" ").each{|x| puts x} 1 2 ["1", "2"] -- __Pascal Bourguignon__