Feature #8683

CSV library can't append to the current row. It should be able to.

Added by Robert Gleeson over 2 years ago. Updated over 2 years ago.



The CSV library can only add new rows, and it provides no way to update the current row after it has been created.

For example:
CSV.generate headers: true do |csv|
csv << ["one"]

["two", "three"].each do |e|
csv << e # This creates a new row, I want to append.
csv.headers << ["two", "three"] # No, this doesn't work either.

Is this possible? I find it hard to believe the API could be that limited and inflexible.


#1 Updated by Robert Gleeson over 2 years ago

I guess I could settle for:

headers = ["one"]
CSV.generate headers: true do
["two", three"].each do |e|
headers << e
csv << headers

but, this is preferable:
headers = ["one"]
CSV.generate headers: true do
csv << headers
["two", three"].each do |e|

#2 Updated by Nobuyoshi Nakada over 2 years ago

  • Status changed from Open to Rejected

CSV class is a reader/writer, not to edit CSV data on memory.
You may want to use CSV::Table instead.

#3 Updated by Robert Gleeson over 2 years ago

@nobu Thanks! I've re-created an example using CSV::Table:
require "csv"
row = CSV::Row.new ["Name"], ["Name"], true
table = CSV::Table.new [row]
table[0] << ["Hair Color", "Hair Color"]
p table.to_csv

It works like I want, but CSV::Row has a strange API. Why does it have a concept of a header, and try to
map it to a value, as if it were a Hash? Couldn't it just be a row of values with no header? And if it is being
treated like a Hash, why isn't the argument just {:header => :value} instead of [:header], [:value] ? It looks
like it even has a method called field(), which may as well be Hash#fetch.

This isn't a bug anymore, but I am curious why it works like that. My problem is solved, so thanks again.

Also available in: Atom PDF