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)
lib/csv/row.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.0.5/lib/csv/row.rb, line 124
def field(header_or_index, minimum_index = 0)
# locate the pair
finder = (header_or_index.is_a?(Integer) || header_or_index.is_a?(Range)) ? :[] : :assoc
pair = @row[minimum_index..-1].public_send(finder, header_or_index)
# return the field if we have a pair
if pair.nil?
nil
else
header_or_index.is_a?(Range) ? pair.map(&:last) : pair.last
end
end
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.