In Ruby, I have an array and I'd like to export it into a csv file. However, I want each value of the array to be on a new row, so that the final csv file is one column containing all the array values. What's the most elegant way to do that?
3 Answers
Lots of ways to do this, but here's one:
require 'csv'
myarray = ["something", "something, also", "\"something\""]
CSV.open("my file.csv", "w") do |f|
myarray.each do |x|
f << [x]
end
end
- require the CSV module
- use it to open a file
- use
<<to write each row, where here a row is just a one-element array with one item from your original array