如果我说得不清楚,请原谅,但这很难用语言来描述。我使用Ruby应用程序逐行接收CSV文件中的值,使用Ruby的tohash.select函数为每行生成所有键-值对的哈希表,然后使用create函数生成行表。
该代码用于从CSV创建数据库表,但是CSV中的许多记录的某些字段/列具有空值。在将CSV中的每一行插入到哈希表中时,我希望将这些空值转换为类似于" null“的字符串。
我曾尝试使用正则表达式将空值替换为字符串,但不起作用。我很可能做错了。
require 'csv'
fields = %w{lVoterUniqueID sAffNumber szStateVoterID sVoterTitle szNameLast szNameFirst szNameMiddle sNameSuffix sGender szSitusAddress szSitusCity sSitusState sSitusZip sHouseNum sUnitAbbr sUnitNum szStreetName sStreetSuffix sPreDir sPostDir szMailAddress1 szMailAddress2 szMailAddress3 szMailAddress4 szMailZip szPhone szEmailAddress dtBirthDate sBirthPlace dtRegDate dtOrigRegDate dtLastUpdate_dt sStatusCode szStatusReasonDesc sUserCode1 sUserCode2 iDuplicateIDFlag szLanguageName szPartyName szAVStatusAbbr szAVStatusDesc szPrecinctName sPrecinctID sPrecinctPortion sDistrictID_0 iSubDistrict_0 szDistrictName_0 sDistrictID_1 iSubDistrict_1 szDistrictName_1 sDistrictID_2 iSubDistrict_2 szDistrictName_2 sDistrictID_3 iSubDistrict_3 szDistrictName_3 sDistrictID_4 iSubDistrict_4 szDistrictName_4 sDistrictID_5 iSubDistrict_5 szDistrictName_5}
if Rails.env.production?
CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
voter_row = row.to_hash.select { |k, v| fields.include?(k)}
Voter.create!(voter_row.to_hash.symbolize_keys)
end
elsif Rails.env.development?
CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
voter_row = row.to_hash.select { |k, v| fields.include?(k)}
Voter.create!(voter_row.to_hash.symbolize_keys)
end
else
CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
voter_row = row.to_hash.select { |k, v| fields.include?(k)}
Voter.create!(voter_row.to_hash.symbolize_keys)
end
end
无论我在哪里使用row.tohash.select,我都希望用空字符串替换空值,这样哈希表中的每个键都有一个相应的字符串(如果没有值,则为“null”)。
https://stackoverflow.com/questions/55405523
复制相似问题