使用Ruby按列合并多个csv

时间:2017-01-19 00:37:03

标签: ruby-on-rails ruby

我有两个csv文件 - customers.csv和test.csv,并希望按列合并两个。例如,

#customers.csv
Customer,Visits,Amount,Review
John,45,1050,Excellent
Marie,20,2400,Amazing,loved it
Martin,30,3600,Could be better,I am pleased
Georgia,10,1500,The best

#test.csv
Average_amount_spent
23
120
120
150

# desired output
Customer,Visits,Amount,Review,Average_amount_spent
John,45,1050,Excellent,23
Marie,20,2400,Amazing,loved it,120
Martin,30,3600,Could be better,I am pleased,120
Georgia,10,1500,The best,150

我找到的解决方案是按行合并。我尝试了以下但我无法正确循环。

COLS = %w{Customer Visits Amount Review Average_amount_spent}
CSV.open("combined.csv", "w") do |row|
    row << COLS
    CSV.foreach("customers.csv", headers: true) do |customer|
        CSV.foreach("test.csv", headers: true) do |amount|
            # all headers except the last element for customer
            row << customer.values_at(*COLS.reverse.drop(1).reverse) + amount.values_at("Average_amount_spent")
        end
    end         
end

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

我认为这会产生所需的输出。

require 'csv'
first_file = CSV.read("customers.csv")
second_file = CSV.read("test.csv")

output = CSV.generate do |csv|
  first_file.each_with_index do |row, i|
    csv << (row + second_file[i])
  end
end

File.write("output.csv", output)
相关问题