From: Phlip Date: 2009-06-03T02:45:09+09:00 Subject: Re: convert 2D array to cute text table with | pipes ? Brian Candler wrote: > Have a look at Ruport's text table rendering code txbut - I should'a made clear I have no mandate to install a whole new library. Does it contain a snippet like this? def row_to_pipes(row, widths) widths = widths.dup return ' ' + row.map{|c| case c when Fixnum c.to_s.rjust(widths.shift) else c.to_s.ljust(widths.shift) end }.join(' | ') + ' ' end def table_to_pipes(table) widths = (0 ... table.first.length).map do |x| table.sort_by{|q| q[x].to_s.length }.last[x].to_s.length end table.map{|r| row_to_pipes(r, widths) }.join("\n") end test 'array to pipes' do assert_equal ' a | b | c ', row_to_pipes(%w(a b c), [1, 2, 1]) end test 'table to pipes' do assert_equal " a | bb | c \n d | 2 | f ", table_to_pipes([%w(a bb c), ['d', 2, 'f']]) end Understand I would never write code this sloppy in production. Really! I'm just letting it out here so if anyone can think of a way to refactor it and DRY it up, we could make a little good-code experiment out of it. It provides the effect I'm after: puts table_to_pipes( [['__concept__', '__frobs', '__zones'], [ 'Unruly Pygmy', 6, 10001 ], [ 'Renonymize', 4, 9999 ], [ 'Opramatic', 4, 10001 ], [ 'El Pollo Psycho', 4, 10002 ], [ 'Mouse Guard', 4, 10003 ], [ 'layuhponit', 4, 10004 ]] ) __concept__ | __frobs | __zones Unruly Pygmy | 6 | 10001 Renonymize | 4 | 9999 Opramatic | 4 | 10001 El Pollo Psycho | 4 | 10002 Mouse Guard | 4 | 10003 layuhponit | 4 | 10004 -- Phlip