0

我有一个 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

如果有多个值,我该如何输出数组内的信息,并用数字匹配?

4

1 回答 1

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}"}
于 2016-07-06T23:38:18.517 回答