如何在Rails的CSV字符串中添加新列 [英] How to add new column in CSV string in rails

查看:77
本文介绍了如何在Rails的CSV字符串中添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加新列并更新CSV响应中的现有值。我如何做更简单,更好的方法来进行以下转换?

I want to add new column and update existing values in CSV response. How can I do simpler and better way of doing the below transformations?

输入

id,name,country
1,John,US
2,Jack,UK
3,Sam,UK

我正在使用以下方法解析csv字符串并添加新列

I am using following method to parse the csv string and add new column

# 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并更新现有值的方法

I am using following method to parse the csv and update existing values

name_hash = { John => Johnny, Jack => Jackie}

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


推荐答案

给出以下用于修改表的参考数据的一个可能选项:

One possible option given the following reference data to be used for modifying the table:

name_hash = {"John" => "Johnny", "Jack" => "Jackie"}
sample_email = {'email' => 'sample@gmail.com'}

只需将表中存储的行转换为哈希表即可:

Just store in rows the table converted to hash:

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"}]



然后根据参考数据修改哈希值(我使用了 Object#then Ruby#2.5的Object#yield_self

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"}]



最后恢复表格:


Finally restore the table:

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

这篇关于如何在Rails的CSV字符串中添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆