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#[]=
row[index] = value → value
row[header, offset] = value → value
row[header] = value → value
lib/csv/row.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.1.3/lib/csv/row.rb, line 339
def []=(*args)
value = args.pop
if args.first.is_a? Integer
if @row[args.first].nil? # extending past the end with index
@row[args.first] = [nil, value]
@row.map! { |pair| pair.nil? ? [nil, nil] : pair }
else # normal index assignment
@row[args.first][1] = value
end
else
index = index(*args)
if index.nil? # appending a field
self << [args.first, value]
else # normal header assignment
@row[index][1] = value
end
end
end
Assigns the field value for the given index or header; returns value.
Assign field value by Integer index:
Example
source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n" table = CSV.parse(source, headers: true) row = table[0] row[0] = 'Bat' row[1] = 3 row # => #<CSV::Row "Name":"Bat" "Value":3>
Counts backward from the last column if index is negative:
Example
row[-1] = 4 row[-2] = 'Bam' row # => #<CSV::Row "Name":"Bam" "Value":4>
Extends the row with nil:nil if positive index is not in the row:
Example
row[4] = 5 row # => #<CSV::Row "Name":"bad" "Value":4 nil:nil nil:nil nil:5>
Raises IndexError if negative index is too small (too far from zero).
Assign field value by header (first found):
Example
source = "Name,Name,Name\nFoo,Bar,Baz\n" table = CSV.parse(source, headers: true) row = table[0] row['Name'] = 'Bat' row # => #<CSV::Row "Name":"Bat" "Name":"Bar" "Name":"Baz">
Assign field value by header, ignoring offset leading fields:
Example
source = "Name,Name,Name\nFoo,Bar,Baz\n" table = CSV.parse(source, headers: true) row = table[0] row['Name', 2] = 4 row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":4>
Append new field by (new) header:
Example
source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n" table = CSV.parse(source, headers: true) row = table[0] row['New'] = 6 row# => #<CSV::Row "Name":"foo" "Value":"0" "New":6>