Username Username - 1 year ago 87
Ruby Question

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

I have a CSV named

, whose headers look like this:


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


How do I use Ruby's
class to put
in column
in column

Answer Source

For your example:"path/to/file.csv", "wb") do |csv|
  fruit, color = ["Banana","Yellow"]
  csv << [fruit, nil, color]

And if you have multiple rows with the same structure:"path/to/file.csv", "wb") do |csv|
  rows.each do |row|
    # Assuming row looks like ["Banana", "Yellow"]
    fruit, color = row
    csv << [fruit, nil, color]

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:"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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download