Class: Perquackey::Table

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/perquackey/table.rb

Instance Method Summary collapse

Constructor Details

#initialize(list = []) ⇒ Table

Returns a new instance of Table.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/perquackey/table.rb', line 5

def initialize(list=[])
  @table = Hash.new { |h, k| h[k] = [] }

  list.each do |word|
    @table[word.length] << word
  end

  if @table.empty?
    @headers = []
    @height  = 0
  else
    @headers = @table.keys.min .. @table.keys.max
    @height  = @table.values.max { |a, b| a.length <=> b.length }.length
  end
end

Instance Method Details

#eachObject



25
26
27
28
29
# File 'lib/perquackey/table.rb', line 25

def each
  @height.times do |row_number|
    yield headers.collect { |length| @table[length][row_number] or ' ' * length}
  end
end

#headersObject



21
22
23
# File 'lib/perquackey/table.rb', line 21

def headers
  @headers
end

#to_sObject



31
32
33
# File 'lib/perquackey/table.rb', line 31

def to_s
  map { |row| row.join(' ') }.join("\n")
end