Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

CSV::Table.new

CSV::Table.new(array_of_rows, headers = nil) → csv_table

Returns a new CSV::Table object.

  • Argument array_of_rows must be an Array of CSV::Row objects.

  • Argument headers, if given, may be an Array of Strings.


Create an empty CSV::Table object:

Example
table = CSV::Table.new([])
table # => #<CSV::Table mode:col_or_row row_count:1>

Create a non-empty CSV::Table object:

Example
rows = [
  CSV::Row.new([], []),
  CSV::Row.new([], []),
  CSV::Row.new([], []),
]
table  = CSV::Table.new(rows)
table # => #<CSV::Table mode:col_or_row row_count:4>

If argument headers is an Array of Strings, those Strings become the table’s headers:

Example
table = CSV::Table.new([], headers: ['Name', 'Age'])
table.headers # => ["Name", "Age"]

If argument headers is not given and the table has rows, the headers are taken from the first row:

Example
rows = [
  CSV::Row.new(['Foo', 'Bar'], []),
  CSV::Row.new(['foo', 'bar'], []),
  CSV::Row.new(['FOO', 'BAR'], []),
]
table  = CSV::Table.new(rows)
table.headers # => ["Foo", "Bar"]

If argument headers is not given and the table is empty (has no rows), the headers are also empty:

Example
table  = CSV::Table.new([])
table.headers # => []

Raises an exception if argument array_of_rows is not an Array object:

Example
# Raises NoMethodError (undefined method `first' for :foo:Symbol):
CSV::Table.new(:foo)

Raises an exception if an element of array_of_rows is not a CSV::Table object:

Example
# Raises NoMethodError (undefined method `headers' for :foo:Symbol):
CSV::Table.new([:foo])
See also #<< #== also in 3.3 · 3.2 · 3.0