1

hash_volumes以下のハッシュに、 hash のキーと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`
    },
}

上記で説明したように、これら 2 つのハッシュをマージできません。私の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 に答える