合并特定值的两个哈希值

时间:2013-08-23 05:02:54

标签: ruby

我正在检查下面的哈希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.

2 个答案:

答案 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