ruby使用数组创建具有不同多个列的csv文件

时间:2020-06-29 17:04:05

标签: ruby rubygems

我是初学者,正在研究红宝石。

我有几个数组,我想将它们写到一个csv文件中。当我们通过excel打开它时,我希望每个数组都对应于csv文件中的一列。

array1 = ["a","b", .......]
array2 = ["1","2", .......]
array3 = ["11","22", .......]

headers = ["letter","number","numberagain",.....]

all = [[array1],[array2],[array3]]

File.open('abc.csv','w') do |f|
 f.write(headers.join("\n"))
 f.write(all.join("\n"))
end

在此代码中,所有内容似乎都在同一列中。如何在excel中使其看起来很漂亮?

当前 now

我想要得到的 wanted

1 个答案:

答案 0 :(得分:2)

array1 = ["a","b"]
array2 = ["1","2"]
array3 = ["11","22"]

headers = ["letter","number","numberagain"]

#not [[array1],...]; array1 is an Array already:
all = [array1, array2, array3].transpose.map{|row| row.join(",")}
# transpose turns cols into rows; join turns each row into a string.
# map takes all those strings and puts them in an Array

File.open('abc.csv','w') do |f|
  f.puts(headers.join(",")) #same as f.puts("letter,number,numberagain")
  f.puts all
end

代码注释中有一些解释。