Skip to content

Instantly share code, notes, and snippets.

@andrewtimberlake
Created December 31, 2008 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewtimberlake/41938 to your computer and use it in GitHub Desktop.
Save andrewtimberlake/41938 to your computer and use it in GitHub Desktop.
Will add a method to Array to print out a pretty text table of a multi-dimensional array
class Array
def tabalize(headings, justifications = nil, out = STDOUT)
raise ArgumentError.new('only works on an array of arrays') if size > 0 && ![0].is_a?(Array)
raise ArgumentError.new('headings, justifications and array elements must all have the same number of elements') if size > 0 && (headings.size != [0].size) && (!justifications.nil? && (headings.size != justifications.size))
sizes = Array.new(headings.size, 0)
headings.each_with_index do |h,i|
sizes[i] = [sizes[i], h.to_s.length].max
end
each do |row|
row.each_with_index do |e, i|
sizes[i] = [sizes[i], e.to_s.length].max
end
end
print_tablalize_lines(out, sizes)
out.write "| "
sizes.each_with_index do |s, i|
out.write " | " if i > 0
out.write headings[i].ljust(s, ' ')
end
out.write " |\n"
print_tablalize_lines(out, sizes)
each do |row|
out.write "| "
sizes.each_with_index do |s, i|
out.write " | " if i > 0
out.write row[i].to_s.send("#{justifications[i].to_s[0..0]}just", s, ' ')
end
out.write " |\n"
end
print_tablalize_lines(out, sizes)
end
private
def print_tablalize_lines(out, sizes)
out.write '+-'
sizes.each_with_index do |s, i|
out.write "-+-" if i > 0
out.write "".ljust(s, '-')
end
out.write "-+\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment