Main Content

Neatly formatting results into a table

Archive - Originally posted on "The Horse's Mouth" - 2010-02-01 22:09:28 - Graham Ellis

Would you like to produce a neat table of results, with the columns just wide enough to take the data? That sounds straightforward, but you can't output anything until you've looked through all the lines to see how long each of them will be.

I was talking about this algorithm today, and this evening I've written it up as an example of formatted printing in Ruby, and posted the complete example on our web site [here]

The trick is to do a "test" format of each of the values in each column first to find the largest, then substitute the column width into the format string for 'real' before you output the data. It's at times like this that you're really glad that a format conversion like %7.2f means "a total width of 7 columns of which 2 are after the decimal place" and not "seven figures before the decimal and 2 after"!


This technique is not appropriate if you're using a variable width font, or if you're generating output for inclusion in a web page (there are some exceptions to this latter)