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#fetch
fetch(header)
fetch(header, default)
fetch(header) {|row| ... }
lib/csv/row.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.0.5/lib/csv/row.rb, line 179
def fetch(header, *varargs)
raise ArgumentError, "Too many arguments" if varargs.length > 1
pair = @row.assoc(header)
if pair
pair.last
else
if block_given?
yield header
elsif varargs.empty?
raise KeyError, "key not found: #{header}"
else
varargs.first
end
end
end
Returns the field value as specified by header.
With the single argument header, returns the field value for that header (first found):
Example
source = "Name,Name,Name\nFoo,Bar,Baz\n" table = CSV.parse(source, headers: true) row = table[0] row.fetch('Name') # => "Foo"
Raises exception KeyError if the header does not exist.
With arguments header and default given, returns the field value for the header (first found) if the header exists, otherwise returns default:
Example
source = "Name,Name,Name\nFoo,Bar,Baz\n" table = CSV.parse(source, headers: true) row = table[0] row.fetch('Name', '') # => "Foo" row.fetch(:nosuch, '') # => ""
With argument header and a block given, returns the field value for the header (first found) if the header exists; otherwise calls the block and returns its return value:
Example
source = "Name,Name,Name\nFoo,Bar,Baz\n" table = CSV.parse(source, headers: true) row = table[0] row.fetch('Name') {|header| fail 'Cannot happen' } # => "Foo" row.fetch(:nosuch) {|header| "Header '#{header} not found'" } # => "Header 'nosuch not found'"