Skip to content

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

instance method

CSV::Row#fields

self.fields(*specifiers) → array_of_fields

Returns field values per the given specifiers, which may be any mixture of:

  • Integer index.

  • Range of Integer indexes.

  • 2-element Array containing a header and offset.

  • Header.

  • Range of headers.

For specifier in one of the first four cases above, returns the result of self.field(specifier); see field.

Although there may be any number of specifiers, the examples here will illustrate one at a time.

When the specifier is an Integer index, returns self.field(index)L

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

When the specifier is a Range of Integers range, returns self.field(range):

Example
row.fields(1..2) # => ["Bar", "Baz"]

When the specifier is a 2-element Array array, returns self.field(array)L

Example
row.fields('Name', 1) # => ["Foo", "Bar"]

When the specifier is a header header, returns self.field(header)L

Example
row.fields('Name') # => ["Foo"]

When the specifier is a Range of headers range, forms a new Range new_range from the indexes of range.start and range.end, and returns self.field(new_range):

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

Returns all fields if no argument given:

Example
row.fields # => ["Foo", "Bar", "Baz"]
See also #field_row? #has_key? #field? #header? also in 3.3 · 3.1 · 3.0