Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # csv_1.csv
- H1,H2,H3
- V11,V22,V33
- V14,V25,V35
- # csv_2.csv
- H1,H4
- V1a,V4b
- V1c,V4d
- H1,H2,H3,H4
- V11,V22,V33,
- V14,V25,V35,
- V1a,,,V4b
- V1c,,,V4d
- require "csv"
- module MergeCsv
- def self.run(csv_1_path, csv_2_path)
- csv_1 = CSV.read(csv_1_path, headers: true)
- csv_2 = CSV.read(csv_2_path, headers: true)
- puts merge(csv_1, csv_2)
- end
- def self.merge(csv_1, csv_2)
- headers = (csv_1.headers + csv_2.headers).uniq.sort
- hash_array = [csv_1, csv_2].flat_map &method(:csv_to_hash_array)
- CSV.generate do |merged_csv|
- merged_csv << headers
- hash_array.each do |row|
- merged_csv << row.values_at(*headers)
- end
- end
- end
- def self.csv_to_hash_array(csv)
- csv.to_a[1..-1].map do |row|
- Hash[csv.headers.zip(row)]
- end
- end
- end
- if(ARGV.length != 2)
- puts "Use: ruby merge_csv.rb <file_path_csv_1> <file_path_csv_2>"
- exit 1
- end
- puts MergeCsv.run(ARGV[0], ARGV[1])
- listPart_A = CSV.read(csv_path_A, headers:true)
- listPart_B = CSV.read(csv_path_B, headers:true)
- listPart_C = CSV.read(csv_path_C, headers:true)
- list = merge(listPart_A,listPart_B,listPart_C)
- def merge(*csvs)
- headers = csvs.map {|csv| csv.headers }.flatten.compact.uniq.sort
- csvs.flat_map(&method(:csv_to_hash_array))
- end
- def csv_to_hash_array(csv)
- csv.to_a[1..-1].map do |row|
- Hash[csv.headers.zip(row)]
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement