Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export a ruby array into a column in a csv file

Tags:

ruby

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?

like image 601
user2573222 Avatar asked Sep 25 '26 10:09

user2573222


1 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
like image 145
glenn mcdonald Avatar answered Sep 28 '26 00:09

glenn mcdonald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!