Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
CSV::Table.new
# File tmp/rubies/ruby-3.3.0/lib/csv/table.rb, line 199
def initialize(array_of_rows, headers: nil)
@table = array_of_rows
@headers = headers
unless @headers
if @table.empty?
@headers = []
else
@headers = @table.first.headers
end
end
@mode = :col_or_row
end
Returns a new CSV::Table object.
-
Argument
array_of_rowsmust be an Array ofCSV::Rowobjects. -
Argument
headers, if given, may be an Array of Strings.
Create an empty CSV::Table object:
table = CSV::Table.new([]) table # => #<CSV::Table mode:col_or_row row_count:1>
Create a non-empty CSV::Table object:
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:
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:
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:
table = CSV::Table.new([]) table.headers # => []
Raises an exception if argument array_of_rows is not an Array object:
# 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:
# Raises NoMethodError (undefined method `headers' for :foo:Symbol): CSV::Table.new([:foo])