如何解析yaml文件?

时间:2017-01-23 12:04:17

标签: ruby yaml

我有一个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的所有值?

1 个答案:

答案 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",这使得理解和使用你的代码变得更加困难。

根据您的目的,eachmapflat_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"]