Last active
May 11, 2018 16:31
-
-
Save garethrees/a0e03130f0ee950ab2643e84e1f55ade to your computer and use it in GitHub Desktop.
Merge CSV columns with same header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
csv = CSV.parse(<<-CSV, headers: true, header_converters: :symbol) | |
id,title,label,label | |
1,fixme,bug,backend | |
CSV | |
row = csv.first | |
row[:labels] = row.map { |k,v| v if k == :label }.compact | |
row[:labels] | |
# => ["bug", "backend"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
class CSV | |
class Row | |
def merge_fields(field, merged_field) | |
self[merged_field] = map { |k,v| v if k == field }.compact | |
end | |
end | |
end | |
csv = CSV.parse(<<-CSV, headers: true, header_converters: :symbol) | |
id,title,label,label | |
1,fixme,bug,backend | |
CSV | |
row = csv.first | |
row.merge_fields(:label, :labels) | |
# => ["bug", "backend"] | |
row[:labels] | |
# => ["bug", "backend"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment