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.
end
csv.headers << ["two", "three"] # No, this doesn't work either.
end
Is this possible? I find it hard to believe the API could be that limited and inflexible.
headers = ["one"]
CSV.generate headers: true do
["two", three"].each do |e|
headers << e
csv << headers
end
end
but, this is preferable:
headers = ["one"]
CSV.generate headers: true do
csv << headers
["two", three"].each do |e|
csv.append_to_current_row(e)
end
end
@nobu (Nobuyoshi Nakada) 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.