我有一个machine.yml文件,如下所示:
---
machines:
A:
ip: ABC
pass: vass
user: A
B:
ip: XYZ
pass: grass
user: B
C:
ip: klm
pass: pass
user: C
我尝试按如下方式解析上述文件:
machines = YAML.load_file('machine.yml')
machines = machines['machines']
## Iterate through entries in YAML file
machines.each_value do |machines|
var = [machines["A"]["ip"], machines["A"]["pass"], machines["B"]["ip"],machines["B"]["pass"], machines["C"]["ip"],machines["C"]["pass"]]
# var should have all the values
end
" var"应该包含所有值作为字符串。但我无法执行上述内容,因为它会抛出错误。如何分别解析YAML的所有值?
答案 0 :(得分:3)
由于您对您感兴趣的密钥进行了硬编码,因此您不需要使用each_values
进行迭代:
machines = YAML.load_file('machine.yml')
machines = machines['machines']
var = [machines["A"]["ip"], machines["A"]["pass"], machines["B"]["ip"],machines["B"]["pass"], machines["C"]["ip"],machines["C"]["pass"]]
首先,您应该尽量不要每次都覆盖相同的变量(machines
)。它被称为" shadowing",这使得理解和使用你的代码变得更加困难。
根据您的目的,each
,map
或flat_map
可以为您提供帮助:
require 'yaml'
yaml_hash = YAML.load_file('machine.yml')
p yaml_hash['machines']
#=> {"A"=>{"ip"=>"ABC", "pass"=>"vass", "user"=>"A"}, "B"=>{"ip"=>"XYZ", "pass"=>"grass", "user"=>"B"}, "C"=>{"ip"=>"klm", "pass"=>"pass", "user"=>"C"}}
yaml_hash['machines'].each do |letter, hash|
p letter
p hash['ip']
p hash['pass']
end
#=>
# "A"
# "ABC"
# "vass"
# "B"
# "XYZ"
# "grass"
# "C"
# "klm"
# "pass"
p yaml_hash['machines'].values
#=> [{"ip"=>"ABC", "pass"=>"vass", "user"=>"A"}, {"ip"=>"XYZ", "pass"=>"grass", "user"=>"B"}, {"ip"=>"klm", "pass"=>"pass", "user"=>"C"}]
p yaml_hash['machines'].values.map { |hash| hash.values_at('ip', 'pass') }
#=> ["ABC", "vass"], ["XYZ", "grass"], ["klm", "pass"]]
p yaml_hash['machines'].values.flat_map { |hash| hash.values_at('ip', 'pass') }
#=> ["ABC", "vass", "XYZ", "grass", "klm", "pass"]