I recently had to typeset a couple of lists of newline-delimiters to LaTeX. Rather than to do the mind-numbing job by hand, I wrote the following script. It takes one argument: the number of columns one wants in the table to have. It then expects the list from standard input, the first row is assumed to be the table captions.

An example:

> to_table 3
Name
Has foo
Has bar
Program1
Yes
No
Program2
No
Yes
^D

Results in

  \begin{tabular}{ccc}
  Name & Has foo & Has bar\\
  \hline
  Program1 & Yes & No\\ 
Program2 & No & Yes
  \end{tabular}

The following is the Ruby script (named to_table in the example).

#!/usr/bin/ruby

# Check the number of arguments.
unless $*.size == 1
  puts "Usage: to_table <column count>" 
  exit 0
end

# Read the list.
n = $*[0].to_i
lines = $stdin.read.split("\n")

# Restructure the list into a table.
rows = []
(0..(lines.size/n-1)).each{ |i|
  rows << lines[(i*n)..(n*(i+1) - 1)]
}

# Typeset the table.
puts <<"end_latex" 
  \\begin{tabular}{#{'c' * n}}
  #{rows[0].join(" & ")}\\\\
  \\hline
  #{rows[1..rows.length-1].map{ |row| row.join(" & ")}.join("\\\\ \n")}
  \\end{tabular}
end_latex

There’s a lot of room for improvements since it was made for a specific purpose. It could be extended to for instance support other delimiters (change lines = $stdin.read.split("\n")), other typesetting formats (change the last bit of code) and the indenting of the result could be improved.

In any case I hope it will save some time for anyone in a similar position.

Sorry, comments are closed for this article.