Username Username - 7 months ago 26
Ruby Question

How do I add a row of data to specific columns?

I have a CSV named

test.csv
, whose headers look like this:

"Fruit","Weight","Color"


In my ruby script, I have an array that looks like this:

["Banana","Yellow"]


How do I use Ruby's
csv
class to put
"Banana"
in column
"Fruit"
and
"Yellow"
in column
"Color"
?

Answer

For your example:

CSV.open("path/to/file.csv", "wb") do |csv|
  fruit, color = ["Banana","Yellow"]
  csv << [fruit, nil, color]
end

And if you have multiple rows with the same structure:

CSV.open("path/to/file.csv", "wb") do |csv|
  rows.each do |row|
    # Assuming row looks like ["Banana", "Yellow"]
    fruit, color = row
    csv << [fruit, nil, color]
  end
end

And if in your real life example your arrays have many more columns (not just two) and you want to add a few empty columns sporadically, you can use the Array#insert method:

CSV.open("path/to/file.csv", "wb") do |csv|
  rows.each do |row|
    # Run one line like this for every empty column you want to add
    # Note that it changes the value of `row`, so if you'd like to 
    # keep it untouched, consider using `dup`
    row.insert(1, nil)
    csv << row
  end
end