我尝试合并2个哈希值,创建一个新值。我试过
Hash[b.map{|k,v| [a[k],v]}
但是当它发现" a"值是空的(无)它没有打印b [k] ......我有类似的东西:
| A | A | | B | B | ====> | C | C |
| key|value| | key|value| ====> |B_value|A_value|
| key|value| | key|value| ====> |B_value|A_value|
| key| nil | | key|value| ====> MISSING
| key|value| | key|value| ====> |B_value|A_value|
钥匙是一样的 我还需要看到零。
如果我尝试以数组格式打印,我可以看到所有内容(包括零):
p = a.map{|k,v| [b[k],v]}
可能地图不是正确的解决方案,还有其他可以给我相同结果的东西吗?
这是我的代码:
header_hostname = Hash.new
working_host = Hash.new
fileset.each do |file|
header = YAML.load_file("output/#{file}")
header.each do |k_header,v_header|
if v_header == "Hostname"
header_hostname = header
end
end
working_host = Hash[header.map{|k, v| [header_hostname[k], v] }]
puts working_host
File.open("tmp/working_hosts.txt","a+") << working_host
Hash的输出如下:
...
Erogazione VlanID: '2390'
" SubnetorIP": 10.*.*.*
" Netmask": 255.255.255.240
" Gateway": 10.*.*.*
...
Backup VlanID: ''
Managment VlanID: ''
Privata HB VlanID: ''
Remote Console VlanID: ''
...
散列
Header = {"98"=>"Erogazione VlanID", "99"=>" SubnetorIP", "100"=>" Netmask", "101"=>" Gateway", "102"=>" Speed(f,g)", "103"=>" Bond(s/n)", "104"=>" Porte", "105"=>" Switch", "106"=>" Slot/Porte", "107"=>" PortePPanel", "108"=>" PortePPanel(bond)", "109"=>"Backup VlanID", "110"=>" SubnetorIP", "111"=>" Netmask", "112"=>" Gateway", "113"=>" Speed(f,g)", "114"=>" Porte", "115"=>" Switch", "116"=>" Slot/Porte", "117"=>" PortePPanel", "135"=>"Remote Console VlanID", "136"=>" SubnetorIP", "137"=>" Netmask", "138"=>" Gateway", "139"=>" Speed(f,g)", "140"=>" Porte", "141"=>" Switch", "142"=>" Slot/Porte", "143"=>" PortePPanel"}
Machine1 = {"98"=>"3315", "99"=>"10.*.*.*", "100"=>"255.255.255.240", "101"=>"10.*.*.*", "102"=>"g", "103"=>"", "104"=>"2.0", "105"=>"", "106"=>"", "107"=>"", "108"=>"", "109"=>"111", "110"=>"10.*.*.*", "111"=>"255.255.255.240", "112"=>"10.*.*.*", "113"=>"g", "114"=>"1.0", "115"=>"", "116"=>"", "117"=>"", "135"=>"111", "136"=>"10.*.*.*", "137"=>"255.255.255.240", "138"=>"10.*.*.*", "139"=>"", "140"=>"", "141"=>"", "142"=>"", "143"=>"" }
这是输出:
output = {"Erogazione VlanID"=>"3315", " SubnetorIP"=>"10.*.*.*", " Netmask"=>"255.255.255.240", " Gateway"=>"10.*.*.*", " Speed(f,g)"=>"", " Bond(s/n)"=>"", " Porte"=>"", " Switch"=>"", " Slot/Porte"=>"", " PortePPanel"=>"", " PortePPanel(bond)"=>"", "Backup VlanID"=>"111", "Remote Console VlanID"=>"111"}
答案 0 :(得分:0)
您的方法似乎运行正常,并且不会在生成的哈希中产生“缺失”条目。
a = { a: 1, b: 2, c: nil, d: 4 }
b = { a: 5, b: 6, c: 7, d: 8 }
c = Hash[a.map{|k,v| [b[k],v]}]
# {5=>1, 6=>2, 7=>nil, 8=>4}
a[:c]
值没有问题,即nil
。它将生成7 => nil
映射,b[:c]
为7
。