Port of Python table construction code to Ruby - not tested yet