输出带格式的yaml文件密钥的所有值

时间:2016-07-06 23:24:36

标签: ruby yaml multiple-value

我有一个yaml文件,它有几个键的多个值:

inbox:
  mary:
          - '-MD-C-LAUREL-ADMIN'
          - '-MD-E-BALTIMORE-ADMIN'
          - '-MD-R1-CAMBRIDGE-ADMIN'
          - '-MD-R2-BELAIR-ADMIN'
          - '-MD-R4-LAUREL-ADMIN'
          - '-MD-R5-HAGERSTWN-ADMIN'
  mike:
          - '-VA-E-Richmond-Admin'
          - '-VA-Richmond-Admin'
          - '-VA-Manassas-Admin'
          - '-VA-Norfolk-Admin'
          - '-VA-Roanoke-Admin'
          - '-VA-Verona-Admin'
  max: '-ATLANTA-RO-ADMIN'

YAML文件'test.yml'

POC = YAML.load_file('test.yml')    

def get_info(name)
  POC['inbox'][name.downcase].nil? ? "** #{name} IS NOT POC **" : POC['inbox'][name.downcase]
end

我想要做的是输出所有这些格式的键,例如运行时:

irb(main):003:0> require 'yaml'
=> true
irb(main):004:0> POC = YAML.load_file('test.yml')
=> {"inbox"=>{"mary"=>["-MD-C-LAUREL-ADMIN", "-MD-E-BALTIMORE-ADMIN", "-MD-R1-CAMBRIDG
E-ADMIN", "-MD-R2-BELAIR-ADMIN", "-MD-R4-LAUREL-ADMIN", "-MD-R5-HAGERSTWN-ADMIN"], "mi
ke"=>["-VA-E-Richmond-Admin", "-VA-Richmond-Admin", "-VA-Manassas-Admin", "-VA-Norfolk
-Admin", "-VA-Roanoke-Admin", "-VA-Verona-Admin"]}}
irb(main):005:0>     def get_info(name)
< "** #{name} IS NOT POC **" : POC['inbox'][name.downcase]
irb(main):007:1>     end
=> :get_info
irb(main):008:0> get_info('mary')
=> ["-MD-C-LAUREL-ADMIN", "-MD-E-BALTIMORE-ADMIN", "-MD-R1-CAMBRIDGE-ADMIN", "-MD-R2-B
ELAIR-ADMIN", "-MD-R4-LAUREL-ADMIN", "-MD-R5-HAGERSTWN-ADMIN"]
irb(main):009:0>

预期的输出是:

Possibly one of the following inboxes: 
1. -MD-C-LAUREL-ADMIN
2. -MD-E-BALTIMORE-ADMIN
3. -MD-R1-CAMBRIDGE-ADMIN
4. -MD-R2-BELAIR-ADMIN
5. -MD-R4-LAUREL-ADMIN
6. -MD-R5-HAGERSTWN-ADMIN

如何输出数组内部的数据以匹配IF有多个值?

1 个答案:

答案 0 :(得分:1)

你的问题根本与YAML无关。这都是关于如何打印带索引的数组。

%w(foo bar baz).each.with_index(1) do |str, i|
  puts "#{i}. #{str}"
end

puts %w(foo bar baz).each.with_index(1).map{|str, i| "#{i}. #{str}"}