gpt4 book ai didi

ruby - 合并特定值的两个哈希值

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

我正在检查哈希值是否为 hash_volumes下面有一个键,其 instance_id与哈希 hash_instance 的键匹配.

hash_volumes = {
:"vol-d16d12b8" => {
:instance_id => "i-4e4ba679",
},
}
hash_instance = {
:"i-4e4ba679" => {
:arch => "x86_64",
},
}

如果是,那么我需要将它合并到 hash_instance .我发现 vol-d16d12b8与实例 i-4e4ba679 匹配因此我想将它与 hash_instance 合并这样最后的hash_instance将如下所示:

hash_instance = {
:"i-4e4ba679" => {
:arch => "x86_64",
:volume => "vol-d16d12b8" # this is new entry to `hash_instance`
},
}

如上所述,我无法合并这两个哈希值。我怀疑我的if陈述是错误的。请看下面我的代码:

hash_volumes.each_key do |x|
hash_instance.each_key do |y|
if hash_volumes[x][:instance_id] == y ## I think this line is the problem
hash_instance[y][:volume] = x
end
end
end

hash_instance

输出:

{
:"i-4e4ba679" => {
:arch => "x86_64"
}
}

上面的代码给出了hash_instance不添加 volume给它。我试过如下,但没有成功:

if hash_volumes[x][:instance_id] == "#{y}"
# => this if statement gives me syntax error

.....

if hash_volumes[x][:instance_id] =~ /"#{y}"/
# => this if statement does not make any changes to above output.

最佳答案

hash_volumes = {
:"vol-d16d12b8" => {
:instance_id => "i-4e4ba679",
},
}

hash_instance = {
:"i-4e4ba679" => {
:arch => "x86_64",
},
}

hash_volumes.each do |key, val|
id = val[:instance_id] #returns nil if the there is no :instance_id key

if id
id_as_sym = id.to_sym

if hash_instance.has_key? id_as_sym
hash_instance[id_as_sym][:volume] = id
end
end
end


--output:--
{:"i-4e4ba679"=>{:arch=>"x86_64", :volume=>"i-4e4ba679"}}

关于ruby - 合并特定值的两个哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18395035/

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