Skip to content
On this page

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

class · Ruby 3.1

CSV::Row

< Object include Enumerable 32 instance methods 1 class methods

CSV::Row

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

The instance may have:

  • Fields: each is an object, not necessarily a String.

  • Headers: each serves a key, and also need not be a String.

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:

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

Output:

Example
#<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:

Example
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:

Example
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:

Example
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 []:

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

Set a field using method []=:

Example
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>

Class methods 1

Instance methods 32

Attributes

row

Read

Internal data format used to compare equality.