End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
CSV::Row#values_at
# File tmp/rubies/ruby-3.2.0/lib/csv/row.rb, line 530
def fields(*headers_and_or_indices)
if headers_and_or_indices.empty? # return all fields--no arguments
@row.map(&:last)
else # or work like values_at()
all = []
headers_and_or_indices.each do |h_or_i|
if h_or_i.is_a? Range
index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
index(h_or_i.begin)
index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
index(h_or_i.end)
new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
(index_begin..index_end)
all.concat(fields.values_at(new_range))
else
all << field(*Array(h_or_i))
end
end
return all
end
end
Alias 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
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):
row.fields(1..2) # => ["Bar", "Baz"]
When the specifier is a 2-element Array array, returns self.field(array)L
row.fields('Name', 1) # => ["Foo", "Bar"]
When the specifier is a header header, returns self.field(header)L
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):
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:
row.fields # => ["Foo", "Bar", "Baz"]