我正在检查下面的哈希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.
答案 0 :(得分:3)
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"}}
答案 1 :(得分:1)
一个简单的实现就是:
hash_instance.each do |k1, v1|
next unless k = hash_volumes.find{|k2, v2| v2[:instance_id].to_sym == k1}
v1[:volume] = k.first
end