"first_name", "2"=>"last_name"} csv_headers = {"1"=>"First Name", "2"=>"L-6ren">
gpt4 book ai didi

ruby:迭代期间无法将新 key 添加到哈希中

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:26 27 4
gpt4 key购买 nike

我有三个哈希:

db_headers = {"1"=>"first_name", "2"=>"last_name"}
csv_headers = {"1"=>"First Name", "2"=>"Last Name"}
csv_records = {"0"=>{"id"=>"11", "first_name"=>"first_0", "Last Name"=>"last_0", "created_at"=>"2014-08-12 17:02:28 UTC", "updated_at"=>"2014-08-12 17:02:28 UTC"}, "1"=>{"id"=>"12", "first_name"=>"first_1", "Last Name"=>"last_1", "created_at"=>"2014-08-12 17:02:28 UTC", "updated_at"=>"2014-08-12 17:02:28 UTC"}}

db_headers 和 csv_headers 通过它们的键匹配。例如,它们的键值“2”分别包含“last_name”和“Last Name”。我的目标是在 db_headers 和 csv_headers 之间的值不同的地方,其中键是相同的,那么我需要用 db_headers 的值交换 csv_records 中的键。因此,例如,csv_records 键将从“Last Name”更改为“last_name”,因为键“2”处的 db_headers 和 csv_headers 值不同。

这是我想出的:

  csv_records.each do |record_key,record_value|
csv_headers.each do |csv_key,csv_value|
if record_value.has_key? csv_value
db_headers.each do |db_key, db_value|
if csv_key == db_key
csv_records[db_value] = csv_records.delete csv_value
break
end
end
break
end
end
end

不幸的是它失败了:

RuntimeError: can't add a new key into hash during iteration
from (irb):12:in `[]='
from (irb):12:in `block (3 levels) in irb_binding'
from (irb):10:in `each'
from (irb):10:in `block (2 levels) in irb_binding'
from (irb):8:in `each'
from (irb):8:in `block in irb_binding'
from (irb):7:in `each'
from (irb):7

这使错误消失了:

csv_records.keys.each do |record_key|
csv_headers.keys.each do |csv_key|
if csv_records[record_key].has_key? csv_headers[csv_key]
db_headers.keys.each do |db_key|
if csv_key == db_key
csv_records[db_headers[db_key]] = csv_records.delete csv_headers[csv_key]
# break is needed becasue csv_key wont exist in next iteration
break
end
end
end
end
end

但 csv_records 现在应该有一个值 last_name,但它继续使用“Last Name”。

最佳答案

迭代 hash.keys 而不是 hash#keys 将生成一个与散列分开的数组,因此您不会在修改散列时弄乱迭代。

关于ruby:迭代期间无法将新 key 添加到哈希中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615126/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com