Ruby在CSV文件中按列从数组写入?

时间:2022-04-19 14:00:09

I would like generate a csv file from severals arrays. This is my code:

我想从几个数组中生成一个csv文件。这是我的代码:

require 'csv'
CSV.open("csvfile.csv", "ab") do |csv|
csv << [array1]
csv << [array2]
csv << [array3]
end

i need this output format:

我需要这个输出格式:

array1,array2,array3
array1,array2,array3
array1,array2,array3
array1,array2,array3
array1,array2,array3

Thx for you help

谢谢你的帮助

2 个解决方案

#1


4  

According to your post, did you mean that array1, array2, array3 stores values of the 3 columns of the table, and the row index is identified by the index of the values in these arrays? You can first group the columns together, do a transpose on the 2-d array and then write to the CSV file row by row.

根据你的文章,你的意思是array1, array2, array3存储了表格中3列的值,而行索引是由这些数组中的值的索引来标识的吗?您可以先将列分组在一起,在二维数组上进行转置,然后逐行写入CSV文件行。

require 'csv'
table = [array1, array2, array3].transpose
CSV.open('csvfile.csv', 'ab') do |csv|
    table.each do |row|
        csv << row
    end
end

You'll get a csv file like this:

你会得到这样的csv文件:

array1[0], array2[0], array3[0]
array1[1], array2[1], array3[1]
array1[2], array2[2], array3[2]
...

#2


1  

Enumerable#zip is the most common method for parallel traversal of multiple collections.

可枚举的#zip是并行遍历多个集合的最常见方法。

require 'csv'

CSV.open('csvfile.csv', 'ab') do |csv|
  array1.zip(array2,array3) { |row| csv << row }
end

#1


4  

According to your post, did you mean that array1, array2, array3 stores values of the 3 columns of the table, and the row index is identified by the index of the values in these arrays? You can first group the columns together, do a transpose on the 2-d array and then write to the CSV file row by row.

根据你的文章,你的意思是array1, array2, array3存储了表格中3列的值,而行索引是由这些数组中的值的索引来标识的吗?您可以先将列分组在一起,在二维数组上进行转置,然后逐行写入CSV文件行。

require 'csv'
table = [array1, array2, array3].transpose
CSV.open('csvfile.csv', 'ab') do |csv|
    table.each do |row|
        csv << row
    end
end

You'll get a csv file like this:

你会得到这样的csv文件:

array1[0], array2[0], array3[0]
array1[1], array2[1], array3[1]
array1[2], array2[2], array3[2]
...

#2


1  

Enumerable#zip is the most common method for parallel traversal of multiple collections.

可枚举的#zip是并行遍历多个集合的最常见方法。

require 'csv'

CSV.open('csvfile.csv', 'ab') do |csv|
  array1.zip(array2,array3) { |row| csv << row }
end