Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. # csv_1.csv
  2. H1,H2,H3
  3. V11,V22,V33
  4. V14,V25,V35
  5.  
  6. # csv_2.csv
  7. H1,H4
  8. V1a,V4b
  9. V1c,V4d
  10.  
  11. H1,H2,H3,H4
  12. V11,V22,V33,
  13. V14,V25,V35,
  14. V1a,,,V4b
  15. V1c,,,V4d
  16.  
  17. require "csv"
  18.  
  19. module MergeCsv
  20. def self.run(csv_1_path, csv_2_path)
  21. csv_1 = CSV.read(csv_1_path, headers: true)
  22. csv_2 = CSV.read(csv_2_path, headers: true)
  23. puts merge(csv_1, csv_2)
  24. end
  25.  
  26. def self.merge(csv_1, csv_2)
  27. headers = (csv_1.headers + csv_2.headers).uniq.sort
  28.  
  29. hash_array = [csv_1, csv_2].flat_map &method(:csv_to_hash_array)
  30.  
  31. CSV.generate do |merged_csv|
  32. merged_csv << headers
  33.  
  34. hash_array.each do |row|
  35. merged_csv << row.values_at(*headers)
  36. end
  37. end
  38. end
  39.  
  40. def self.csv_to_hash_array(csv)
  41. csv.to_a[1..-1].map do |row|
  42. Hash[csv.headers.zip(row)]
  43. end
  44. end
  45. end
  46.  
  47. if(ARGV.length != 2)
  48. puts "Use: ruby merge_csv.rb <file_path_csv_1> <file_path_csv_2>"
  49. exit 1
  50. end
  51.  
  52. puts MergeCsv.run(ARGV[0], ARGV[1])
  53.  
  54. listPart_A = CSV.read(csv_path_A, headers:true)
  55.  
  56. listPart_B = CSV.read(csv_path_B, headers:true)
  57.  
  58. listPart_C = CSV.read(csv_path_C, headers:true)
  59.  
  60. list = merge(listPart_A,listPart_B,listPart_C)
  61.  
  62. def merge(*csvs)
  63. headers = csvs.map {|csv| csv.headers }.flatten.compact.uniq.sort
  64. csvs.flat_map(&method(:csv_to_hash_array))
  65. end
  66.  
  67. def csv_to_hash_array(csv)
  68. csv.to_a[1..-1].map do |row|
  69. Hash[csv.headers.zip(row)]
  70. end
  71. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement