3

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?

0

3 Answers 3

2

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
0
[
  ["foo", "bar"],
  ["baz", "woo"],
]
.flatten.map{|e| [e]}
# =>
# [
#   ["foo"],
#   ["bar"],
#   ["baz"],
#   ["woo"],
# ]
0

You can just write elements of array in each line:

ary = ["goat", "cat", ["alien", "planet"]].flatten

File.open("a.csv", "w") do |f|
  f.write(ary.join("\n"))
end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.