Created
December 31, 2008 09:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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