我想添加新列并更新CSV响应中的现有值。如何进行以下转换的更简单更好的方法?
输入
id,name,country
1,John,US
2,Jack,UK
3,Sam,UK
我正在使用以下方法解析csv字符串并添加新列
# Parse original CSV
rows = CSV.parse(csv_string, headers: true).collect do |row|
hash = row.to_hash
# Merge additional data as a hash.
hash.merge('email' => 'sample@gmail.com')
end
# Extract column names from first row of data
column_names = rows.first.keys
# Generate CSV after transformation of csv
csv_response = CSV.generate do |csv|
csv << column_names
rows.each do |row|
# Extract values for row of data
csv << row.values_at(*column_names)
end
end
我正在使用以下方法解析csv并更新现有值
name_hash = {“ John” =>“ Johnny”,“ Jack” =>“ Jackie”}
rows = CSV.parse(csv_string, headers: true).collect do |row|
hash = row.to_hash
hash['name'] = name_hash[hash['name']] if name_hash[hash['name']] != nil
hash
end
# Extract column names from first row of data
column_names = rows.first.keys
# Generate CSV after transformation of csv
csv_response = CSV.generate do |csv|
csv << column_names
rows.each do |row|
# Extract values for row of data
csv << row.values_at(*column_names)
end
end
答案 0 :(得分:1)
给出了以下用于修改表格的参考数据的一个可能选项:
name_hash = {"John" => "Johnny", "Jack" => "Jackie"}
sample_email = {'email' => 'sample@gmail.com'}
只需将转换为哈希的表存储在行中即可
rows = CSV.parse(csv_string, headers: true).map(&:to_h)
#=> [{"id"=>"1", "name"=>"John", "country"=>"US"}, {"id"=>"2", "name"=>"Jack", "country"=>"UK"}, {"id"=>"3", "name"=>"Sam", "country"=>"UK"}]
rows.each { |h| h.merge!(sample_email).then {|h| h['name'] = name_hash[h['name']] if name_hash[h['name']] } }
#=> [{"id"=>"1", "name"=>"Johnny", "country"=>"US", "email"=>"sample@gmail.com"}, {"id"=>"2", "name"=>"Jackie", "country"=>"UK", "email"=>"sample@gmail.com"}, {"id"=>"3", "name"=>"Sam", "country"=>"UK", "email"=>"sample@gmail.com"}]
csv_response = CSV.generate(headers: rows.first.keys) { |csv| rows.map(&:values).each { |v| csv << v } }
所以您现在拥有:
puts csv_response
# id,name,country,email
# 1,Johnny,US,sample@gmail.com
# 2,Jackie,UK,sample@gmail.com
# 3,Sam,UK,sample@gmail.com