1

Open two csv files.The field name and values label, sample are the same in both files, combine the average_old and average_new to to third csv. I could find some of the results indicating faster csv but it's totally new to me. Any small snippet is appreciated.If the row exists in only one file I want to keep it in the new file.

For example:

File1.csv

label,sample,average_old
t1,10,12
t2,11,13

File2.csv

label,sample,average_new
t1,10,16
t2,11,15

File3.csv should be

label,sample,average_old,average_new
t1,10,12,16
t2,11,13,15
0

1 Answer 1

2
require 'csv'
CSV.foreach('/tmp/File2.csv').inject(
  CSV.foreach('/tmp/File1.csv').inject({}) do |memo, row| 
    (memo[row.first] ||= []) << row
    memo
  end
) do |memo, row| 
  (memo[row.first] ||= []) << row
  memo
end.map(&:flatten).map(&:uniq)

#⇒ [
#    ["label", "sample", "average_old", "average_new"], 
#    ["t1", "10", "12", "16"], 
#    ["t2", "11", "13", "15"]
#  ]

Writing this array to file should be easy.

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.