Skip to content

Instantly share code, notes, and snippets.

@ericgj
Created January 30, 2011 15:23
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 ericgj/802940 to your computer and use it in GitHub Desktop.
Save ericgj/802940 to your computer and use it in GitHub Desktop.
class Table
def initialize(data = [], options = {})
check_type data
data.each do |row|
check_type row
check_length row, data.first.length
end
@header_support = options[:headers]
set_headers(data.shift) if @header_support
@rows = data
end
def add_row(new_row, pos=nil)
check_type new_row
check_length new_row, @rows.first.length
i = pos.nil? ? @rows.length : pos
@rows.insert(i, new_row)
end
def add_column(col, pos=nil)
check_type col
check_length col, @rows.length
i = pos.nil? ? @rows.first.length : pos
if @header_support
headers.insert(i, col.shift)
end
@rows.each do |row|
row.insert(i, col.shift)
end
end
private
def check_type(data)
raise ArgumentError, "Input is not an array" \
unless Array === data
end
def check_length(data, expected)
raise ArgumentError, "Input length is inconsistent" \
unless data.length == expected
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment