Method: CSV::Row#field
- Defined in:
- lib/csv/row.rb
#field(header_or_index, minimum_index = 0) ⇒ Object Also known as: []
:call-seq:
field(index) -> value
field(header) -> value
field(header, offset) -> value
Returns the field value for the given index
or header
.
Fetch field value by Integer index:
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:
row.field(-1) # => "0"
row.field(-2) # => "foo"
Returns nil
if index
is out of range:
row.field(2) # => nil
row.field(-3) # => nil
Fetch field value by header (first found):
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:
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.
203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/csv/row.rb', line 203 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].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 |