1

我正在检查hash_volumes下面的哈希是否有一个instance_id与 hash 匹配的键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.
4

2 回答 2

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"}}
于 2013-08-23T05:22:19.970 回答
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
于 2013-08-23T05:31:37.677 回答