Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename CSV headers in Ruby?

Tags:

ruby

csv

I have a CSV file and I want to merge these records into an existing CSV file. However, the two files have headers that are named differently. How can I cleanly and efficiently rename the CSV headers so that the match the file I'm merging to?

like image 779
wise_gremlin Avatar asked Feb 11 '23 05:02

wise_gremlin


1 Answers

Answer:

CSV::HeaderConverters[:map_to_main] = lambda do |header|
  # work your magic here
  header
end
CSV.open(file,
  headers: true,
  header_converters: :map_to_main).to_a.map(&:to_hash)
like image 73
wise_gremlin Avatar answered Feb 23 '23 13:02

wise_gremlin