Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

CSV::Row#[]

[](header_or_index, minimum_index = 0)

Alias of #field

Returns the field value for the given index or header.


Fetch field value by Integer index:

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

Counts backward from the last column if index is negative:

Example
row.field(-1) # => "0"
row.field(-2) # => "foo"

Returns nil if index is out of range:

Example
row.field(2) # => nil
row.field(-3) # => nil

Fetch field value by header (first found):

Example
source = "Name,Name,Name\nFoo,Bar,Baz\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.field('Name') # => "Foo"

Fetch field value by header, ignoring offset leading fields:

Example
source = "Name,Name,Name\nFoo,Bar,Baz\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.field('Name', 2) # => "Baz"

Returns nil if the header does not exist.

See also #field #[]= #== #<< also in 3.2 · 3.1 · 3.0