gpt4 book ai didi

ruby - 如何解析yaml文件?

转载 作者:行者123 更新时间:2023-12-02 20:52:24 25 4
gpt4 key购买 nike

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

最佳答案

你的代码

由于您对感兴趣的键进行了硬编码,因此无需使用 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"]]

备选

首先,你应该尽量不要每次都覆盖同一个变量(机器)。这称为“阴影”,它使您的代码更难理解和使用。

根据你想做什么,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"]

关于ruby - 如何解析yaml文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com