Skip to content

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

instance method

CSV::Row#fetch

fetch(header) → value
fetch(header, default) → value
fetch(header) {|row| ... } → value

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'"
See also #each_pair #field #each #field? also in 3.3 · 3.2 · 3.0