Dumping Tabular Data with Hirb

Sometimes you just want to dump an ASCII table of data:

In the past when I wanted to dump some tabular data to the console or to a log I used Ruport. This works well enough, but Ruport is an awfully heavy dependency for such a simple task.

The other day I ported some data dumping code to use Hirb instead. Hirb is about data formatting and formatting alone, rather than being a full reporting framework, so it’s a much lighter dependency. I had tried to make the switch once before, but been confused by the Hirb API. This time at Dan Mayer‘s suggestion I used the Churn gem as an example, and got it working in a few minutes.

There’s already plenty of Hirb documentation on Tagaholic’s site, but most of it seems aimed at more advanced use cases. If all you want to do is format an Array of arbitrary objects as a table, here’s how to do it:

(Example adapted from DACS.)

The :fields key tells Hirb which methods to use as columns – otherwise you’d just get a single-column table with the string representations of the objects. The :headers key lets you specify nice human-friendly headers for the columns. The setting :description to false tells Hirb not to print a line below the table with the total number of rows.