Method: Text::Table#initialize

Defined in:
lib/text-table/table.rb

#initialize(options = {}) {|_self| ... } ⇒ Table

You could create a Text::Table object by passing an options hash:

    table = Text::Table.new(:head => ['A', 'B'], :rows => [['a1', 'b1'], ['a2', 'b2']])

Or by passing a block:

    table = Text::Table.new do |t|
      t.head = ['A', 'B']
      t.rows = [['a1', 'b1']]
      t.rows << ['a2', 'b2']
    end

    table.to_s

    #    +----+----+
    #    | A  | B  |
    #    +----+----+
    #    | a1 | b1 |
    #    | a2 | b2 |
    #    +----+----+

==== Aligning Cells and Spanning Columns

Alignment and column span can be specified by passing a cell as a Hash object.

The acceptable aligments are <tt>:left</tt>, <tt>:center</tt> and <tt>:right</tt>.

Cells and footers are aligned to the left by default, while headers are centered by default.

    table = Text::Table.new do |t|
      t.head = ['Heading A', 'Heading B']
      t.rows << ['a1', 'b1']
      t.rows << ['a2', {:value => 'b2', :align => :right}]
      t.rows << ['a3', 'b3']
      t.rows << [{:value => 'a4', :colspan => 2, :align => :center}]
    end

    puts table

    #    +-----------+-----------+
    #    | Heading A | Heading B |
    #    +-----------+-----------+
    #    | a1        | b1        |
    #    | a2        |        b2 |
    #    | a3        | b3        |
    #    |          a4           |
    #    +-----------+-----------+

==== Adding a Separator

You can add a separator by inserting <tt>:separator</tt> symbols between the rows.

    Text::Table.new :rows => [
      ['a', 'b'],
      ['c', 'd'],
      :separator,
      ['e', 'f'],
      :separator,
      ['g', 'h']
    ]

    #    +---+---+
    #    | a | b |
    #    | c | d |
    #    +---+---+
    #    | e | f |
    #    +---+---+
    #    | g | h |
    #    +---+---+

==== Other Options

Cell padding and table boundaries can be modified.

    Text::Table.new :rows => [['a', 'b'], ['c', 'd']],
                    :horizontal_padding    => 3,
                    :vertical_boundary     => '=',
                    :horizontal_boundary   => ':',
                    :boundary_intersection => 'O'

    #    O=======O=======O
    #    :   a   :   b   :
    #    :   c   :   d   :
    #    O=======O=======O

Yields:

  • (_self)

Yield Parameters:

  • _self (Text::Table)

    the object that the method was called on



120
121
122
123
124
125
126
127
128
129
# File 'lib/text-table/table.rb', line 120

def initialize(options = {})
  @vertical_boundary     = options[:vertical_boundary    ] || '-'
  @horizontal_boundary   = options[:horizontal_boundary  ] || '|'
  @boundary_intersection = options[:boundary_intersection] || '+'
  @horizontal_padding    = options[:horizontal_padding   ] || 1
  @head = options[:head]
  @rows = options[:rows] || []
  @foot = options[:foot]
  yield self if block_given?
end