class CSV::Row

CSV::Row

A CSV::Row instance represents a CSV table row. (see class CSV).

The instance may have:

Instance Methods

CSV::Row has three groups of instance methods:

Creating a CSV::Row Instance

Commonly, a new CSV::Row instance is created by parsing CSV source that has headers:

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.each {|row| p row }

Output:

#<CSV::Row "Name":"foo" "Value":"0">
#<CSV::Row "Name":"bar" "Value":"1">
#<CSV::Row "Name":"baz" "Value":"2">

You can also create a row directly. See ::new.

Headers

Like a CSV::Table, a CSV::Row has headers.

A CSV::Row that was created by parsing CSV source inherits its headers from the table:

source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
row = table.first
row.headers # => ["Name", "Value"]

You can also create a new row with headers; like the keys in a Hash, the headers need not be Strings:

row = CSV::Row.new([:name, :value], ['foo', 0])
row.headers # => [:name, :value]

The new row retains its headers even if added to a table that has headers:

table << row # => #<CSV::Table mode:col_or_row row_count:5>
row.headers # => [:name, :value]
row[:name] # => "foo"
row['Name'] # => nil

Accessing Fields

You may access a field in a CSV::Row with either its Integer index (Array-style) or its header (Hash-style).

Fetch a field using method []:

row = CSV::Row.new(['Name', 'Value'], ['foo', 0])
row[1] # => 0
row['Value'] # => 0

Set a field using method []=:

row = CSV::Row.new(['Name', 'Value'], ['foo', 0])
row # => #<CSV::Row "Name":"foo" "Value":0>
row[0] = 'bar'
row['Value'] = 1
row # => #<CSV::Row "Name":"bar" "Value":1>