使用ruby显示来自yaml的特定条件散列

but5z9lq  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(137)

我正在尝试使用ruby显示来自yaml文件的特定散列/数组

offices:
  location: xyz
  employees:
    jack:
      id: jack_001
      role: developer
      address: uk
      primary_contact: xyz@gmail.com
    tom: 
      id: tom_001
      role: tester
      address: usa
      primary_contact: abc@gmail.com

现在从上面我想显示的条件与ruby
例如,如果employee_name == jack,则为我提供primary_contact和角色值
我正在尝试以下代码

require 'yaml'
yaml = YAML::load(File.open("/etc/puppetlabs/facter/facts.d/details.yaml"))
yaml_employee = yaml['offices']['employees']
puts yaml_employee
yaml_employee.each do |key, value|
if yaml_employee[key] == "jack"
 puts yaml_employee[key]['role']
 puts yaml_employee[key]['primary_contact']

未打印预期值,如下所示
如果我使用上面的代码,预期的输出应该打印雇员的姓名jack,角色是开发人员,主要联系人是xyz@gmail.com
预期输出插孔,开发人员,xyz@gmail.com
现在从上面我想显示的条件与ruby
例如,如果employee_name == jack,则为我提供primary_contact和角色值
我正在尝试以下代码

require 'yaml'
yaml = YAML::load(File.open("/etc/puppetlabs/facter/facts.d/details.yaml"))
yaml_employee = yaml['offices']['employees']
puts yaml_employee
yaml_employee.each do |key, value|
if yaml_employee[key] == "jack"
 puts yaml_employee[key]['role']
 puts yaml_employee[key]['primary_contact']

未打印预期值,如下所示
如果我使用上面的代码,预期的输出应该打印雇员的姓名jack,角色是开发人员,主要联系人是xyz@gmail.com
预期输出插孔,开发人员,xyz@gmail.com
我还想打印雇员姓名下的每个块,例如jack和tom,但在雇员姓名为未知值的情况下。

tp5buhyn

tp5buhyn1#

不需要每次循环都从散列中检索数据,只需要适当的键就可以从散列中获取数据
请尝试以下代码

require 'yaml'

yaml_str = <<~YAML_STR
---
offices:
  location: xyz
  employees:
    jack:
      id: jack_001
      role: developer
      address: uk
      primary_contact: xyz@gmail.com
    tom: 
      id: tom_001
      role: tester
      address: usa
      primary_contact: abc@gmail.com
YAML_STR

yaml = YAML::load(yaml_str)

yaml_employee = yaml['offices']['employees']
puts "Employee Data"
puts yaml_employee

puts "jack Info"

puts emp_name = "jack"
emp_info = yaml_employee[emp_name]
puts emp_info['role']
puts emp_info['primary_contact']

输出功率
员工数据

{"jack"=>{"id"=>"jack_001", "role"=>"developer", "address"=>"uk", "primary_contact"=>"xyz@gmail.com"}, "tom"=>{"id"=>"tom_001", "role"=>"tester", "address"=>"usa", "primary_contact"=>"abc@gmail.com"}}
jack Info
jack
developer
xyz@gmail.com

相关问题