如何在Ruby中重命名CSV标头?

时间:2021-08-09 23:26:07

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?

我有一个CSV文件,我想将这些记录合并到现有的CSV文件中。但是,这两个文件的标题名称不同。如何干净有效地重命名CSV标题,以便匹配我正在合并的文件?

1 个解决方案

#1


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)

#1


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)