Home > Net >  Simple array to CSV in ruby with new line added
Simple array to CSV in ruby with new line added

Time:09-08

I have the following script:

require 'CSV'

colors = ["red", "blue", "green"]

CSV.open("valid_urls.csv", "w") do |csv|
    csv << colors
end

With this code, the contents of my CSV looks like this:

red,blue,green

However, what I want is this:

red
blue
green

I tried doing something like colors = ["red", "blue", "green"].join "\n" but I get a undefined methodcollect'` error.

CodePudding user response:

when you append an flat array to a csv, it makes a single row. It looks like you want 3 rows? If so, then:

require 'CSV'

colors = ["red", "blue", "green"]

CSV.open("valid_urls.csv", "w") do |csv|
    colors.each do |color|
      csv << [color]
    color
end

does that give you what you're looking for?

  • Related