Created
April 8, 2009 04:28
-
-
Save burke/91634 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Table | |
def initialize | |
@widths = [] | |
@data = [] | |
yield self if block_given? | |
end | |
def headers(*headers) | |
@headers = headers | |
headers.each do |header| | |
@widths << ( header.split(/\s+/).map{|e|e.size}.max + 2) | |
end | |
end | |
def data(*columns) | |
@data << columns | |
columns.each_with_index do |column,i| | |
@widths[i] = [column.to_s.size+2, @widths[i]].max | |
end | |
end | |
def to_s | |
ret = "" | |
ret << format_headers | |
ret << divider | |
@data.each {|row| ret << format_row(row)} | |
ret | |
end | |
private | |
# Here we allot two rows for headers, breaking on word boundaries. | |
# This is a fragile system, but it works for the assignment. | |
def format_headers | |
row_1 = [] | |
row_2 = [] | |
@headers.each_with_index do |header,i| | |
if header.size > @widths[i] | |
row_1[i] = header.split[0] | |
row_2[i] = header.split[1] | |
else | |
row_1[i] = header | |
row_2[i] = "" | |
end | |
end | |
ret = "" | |
ret << @widths.map{|el|"%-#{el}s"}.join('') % row_1 | |
ret << "\n" | |
ret << @widths.map{|el|"%-#{el}s"}.join('') % row_2 | |
ret << "\n" | |
ret | |
end | |
def format_row(row) | |
@widths.map{|el|"%-#{el}d"}.join('') % row + "\n" | |
end | |
def divider | |
"-" * @widths.inject{|a,v|a+v} + "\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment