Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add transpose! method to table

Allows for tables like:
| Name   | Dave |
| Age    | 99   |
| Height | 6ft  |
  • Loading branch information...
commit 21f793fcc1cd16c05166ad4e0a363f4481e3baee 1 parent 0cc43b8
Dave Lyon authored

Showing 2 changed files with 36 additions and 6 deletions. Show diff stats Hide diff stats

  1. +15 6 lib/turnip/table.rb
  2. +21 0 spec/table_spec.rb
21 lib/turnip/table.rb
@@ -10,29 +10,38 @@ def initialize(raw)
10 10 end
11 11
12 12 def headers
13   - @raw.first
  13 + raw.first
14 14 end
15 15
16 16 def rows
17   - @raw.drop(1)
  17 + raw.drop(1)
18 18 end
19 19
20 20 def hashes
21 21 rows.map { |row| Hash[headers.zip(row)] }
22 22 end
23   -
  23 +
24 24 def rows_hash
25 25 return @rows_hash if @rows_hash
26 26 verify_table_width(2)
27 27 @rows_hash = self.class.new(raw.transpose).hashes[0]
28 28 end
29 29
  30 + def transpose!
  31 + raise %{The table must have exactly #{width} columns} unless width == 2
  32 + @raw = raw.transpose
  33 + end
  34 +
30 35 def each
31   - @raw.each { |row| yield(row) }
  36 + raw.each { |row| yield(row) }
32 37 end
33   -
  38 +
34 39 private
35   -
  40 +
  41 + def width
  42 + raw[0].size
  43 + end
  44 +
36 45 def verify_table_width(width)
37 46 raise %{The table must have exactly #{width} columns} unless raw[0].size == width
38 47 end
21 spec/table_spec.rb
@@ -39,6 +39,27 @@
39 39 end
40 40 end
41 41
  42 + describe '#transpose' do
  43 + context "when table is 2 columns wide" do
  44 +
  45 + let(:raw) { [["Name", "Dave"], ["Age", "99"], ["Height", "6ft"]] }
  46 +
  47 + it 'transposes the raw table' do
  48 + table.transpose!
  49 + table.hashes.should == [{ "Name" => "Dave", "Age" => "99", "Height" => "6ft" }]
  50 + end
  51 + end
  52 +
  53 + context "when table is greater than 2 columns wide" do
  54 +
  55 + let(:raw) { [["a", "b", "c"], ["1", "2", "3"]] }
  56 +
  57 + it 'raises an error' do
  58 + expect { table.transpose! }.to raise_error
  59 + end
  60 + end
  61 + end
  62 +
42 63 describe '#rows_hash' do
43 64 let(:raw) { [['foo', 'moo'], ['bar', '55']] }
44 65 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.
Something went wrong with that request. Please try again.