无法将csv数据放入哈希表中

3

我有一个包含两列的CSV文件:

PPS_Id Amount
123    100
1234   150

我使用以下代码从这个文件中读取数据并将其插入到数组中:

CSV.foreach("filename.CSV", headers: true) do |row|
  file_details << row.inspect # hash
end

我尝试将file_details中的数据推入一个哈希表中,以PPS_Id为键,Amount为值。我使用以下代码:

file_details_hash = Hash.new

file_details.each { |x|  
  file_details_hash[x['PPS_Id']] = x['Amount']
}

但当我打印结果时,什么也没有,只有{"PPS_Id"=>"Amount"}。 请问你能帮忙吗?
3个回答

1
首先,您将字符串收集到数组中(请参见String#inspect):
file_details << row.inspect

在此之后,您可以在该字符串上调用String#[]函数:
x['PPS_Id'] #⇒ "PPS_Id", because string contains this substring

尽管如此,您的代码仅存在错误。也许您可以使用以下方式实现所需功能:
csv = CSV.parse(File.read("filename.CSV"), col_sep: "\s")
csv[1..-1].to_h
#⇒ {
#    "123" => "100",
#   "1234" => "150"
# }

1
使用 inspect 会将你的 CSV 行保存为字符串,因此显然你无法得到需要的内容。相反,尝试使用以下方法:
file_details = CSV.read("filename.csv")

直接读取CSV将创建一个2D数组,您可以对其进行迭代,看起来像这样:[["PPS_Id", "Amount"], ["123", "100"], ["1234", "150"]] 从那里,您可以稍微修改您的方法:
file_details.each do |key, value|
  file_details_hash[key] = value
end

为了接收像这样的哈希表:{"PPS_Id"=>"Amount", "123"=>"100", "1234"=>"150"}

1
Hash[*[["PPS_Id", "Amount"], ["123", "100"], ["1234", "150"]].flatten] => {"PPS_Id"=>"Amount", "123"=>"100", "1234"=>"150"} - Roman Kiselenko

1

您的代码已修改以使其正常工作

您需要为您的csv指定列分隔符,并删除inspect

require 'csv'

file_details = []
CSV.foreach("filename.CSV", headers: true, col_sep: "\s" ) do |row|
  file_details << row
end

file_details_hash = Hash.new
file_details.each { |x|
  file_details_hash[x['PPS_Id']] = x['Amount']
}

p file_details_hash
#=> {"123"=>"100", "1234"=>"150"}

现在它返回了你期望得到的结果。

更短的解决方案

读取csv文件,删除第一行(标题),并转换为哈希表:

p CSV.read("filename.CSV", col_sep: "\s").drop(1).to_h
#=> {"123"=>"100", "1234"=>"150"}

我更倾向于使用以下代码,按照您的逻辑:CSV.foreach("filename.CSV", headers: false) do |row| file_details[row[0]] = row[1] end - d_luffy_de

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接