Transform ruby array to tex table
This has probably been written in many projects, anyways here is the code I wrote up to convert a ruby table / 2-dimensional array / array of arrays to a tex table:
def to_tex(table, user_opts = {})
default_opts = {:center => true, :sep_cols => true, :col_align => 'l'}
opts = default_opts.merge(user_opts)
lines = ['\begin{table}[!ht]']
lines << '\begin{center}' if opts[:center]
headers = table.first
lines << "\\begin{tabular}{#{headers.map{opts[:col_align]}.join(opts[:sep_cols] ? '|' : '')}}"
headers_in_bold = headers.map{|header| (header.nil? or header.empty?) ? '' : "\\textbf{#{header}}"}
lines << headers_in_bold.join(' & ') + '\\\\ \\hline'
table[1..-1].each{|row| lines << row.join(' & ') + '\\\\'}
lines << '\end{tabular}'
lines << '\end{center}' if opts[:center]
lines << "\\caption{#{opts[:caption]}}" if opts[:caption]
lines << "\\label{#{opts[:label]}}" if opts[:label]
lines << '\end{table}'
lines.join("\n")
end
The code assumes the first row is the header row and will put the column titles in bold. A horizontal line is put below the headers and then your rows are printed.
There are a some user definable options: the use of centering, caption, label, column alignment and the use of column separation. Some of them have a default value in the default_opts hash.
Usage example:
table = [[nil, 'Even?', 'Square']]
10.times{|i| table << [i, (i % 2 == 0) ? 'Y' : 'N', i**2]}
puts to_tex(table, :col_align => 'c', :caption => 'Table of numbers and basic properties')
This gives:
\begin{table}[!ht]
\begin{center}
\begin{tabular}{c|c|c}
& \textbf{Even?} & \textbf{Square}\\ \hline
0 & Y & 0\\
1 & N & 1\\
2 & Y & 4\\
3 & N & 9\\
4 & Y & 16\\
5 & N & 25\\
6 & Y & 36\\
7 & N & 49\\
8 & Y & 64\\
9 & N & 81\\
\end{tabular}
\end{center}
\caption{Table of numbers and basic properties}
\end{table}
I hope this helps.
