Skip to content

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

instance method

CSV::Row#field

field(index)
field(header)
field(header, offset)

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? #fetch #each_pair #field_row? also in 3.3 · 3.2 · 3.1