Method: CSV::Table#initialize
- Defined in:
- lib/csv/table.rb
#initialize(array_of_rows, headers: nil) ⇒ Table
:call-seq:
CSV::Table.new(array_of_rows, headers = nil) -> csv_table
Returns a new CSV::Table object.
-
Argument
array_of_rowsmust be an Array of CSV::Row objects. -
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])
199 200 201 202 203 204 205 206 207 208 209 210 211 |
# File '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 |