Permalink
Browse files

Add transpose! method to table

Allows for tables like:
| Name   | Dave |
| Age    | 99   |
| Height | 6ft  |
  • Loading branch information...
1 parent 0cc43b8 commit 21f793fcc1cd16c05166ad4e0a363f4481e3baee @davelyon committed Feb 14, 2012
Showing with 36 additions and 6 deletions.
  1. +15 −6 lib/turnip/table.rb
  2. +21 −0 spec/table_spec.rb
View
@@ -10,29 +10,38 @@ def initialize(raw)
end
def headers
- @raw.first
+ raw.first
end
def rows
- @raw.drop(1)
+ raw.drop(1)
end
def hashes
rows.map { |row| Hash[headers.zip(row)] }
end
-
+
def rows_hash
return @rows_hash if @rows_hash
verify_table_width(2)
@rows_hash = self.class.new(raw.transpose).hashes[0]
end
+ def transpose!
+ raise %{The table must have exactly #{width} columns} unless width == 2
+ @raw = raw.transpose
+ end
+
def each
- @raw.each { |row| yield(row) }
+ raw.each { |row| yield(row) }
end
-
+
private
-
+
+ def width
+ raw[0].size
+ end
+
def verify_table_width(width)
raise %{The table must have exactly #{width} columns} unless raw[0].size == width
end
View
@@ -39,6 +39,27 @@
end
end
+ describe '#transpose' do
+ context "when table is 2 columns wide" do
+
+ let(:raw) { [["Name", "Dave"], ["Age", "99"], ["Height", "6ft"]] }
+
+ it 'transposes the raw table' do
+ table.transpose!
+ table.hashes.should == [{ "Name" => "Dave", "Age" => "99", "Height" => "6ft" }]
+ end
+ end
+
+ context "when table is greater than 2 columns wide" do
+
+ let(:raw) { [["a", "b", "c"], ["1", "2", "3"]] }
+
+ it 'raises an error' do
+ expect { table.transpose! }.to raise_error
+ end
+ end
+ end
+
describe '#rows_hash' do
let(:raw) { [['foo', 'moo'], ['bar', '55']] }
it 'converts this table into a Hash where the first column is used as keys and the second column is used as values' do

0 comments on commit 21f793f

Please sign in to comment.