2016-07-06 70 views
0

我有一個具有多個值的一對夫婦鍵YAML文件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 

我該如何去輸出數組內的信息與數字匹配如果有多個值?

+1

這真的幫助我們,如果你剝去IRB輸出,只顯示錶達式和它們的輸出,而不是IRB提示。我們很多人在我們的編輯中使用「Seeing Is Believing」,這使得選擇性地顯示類似IRB的輸出非常容易,沒有噪音。保持代碼清潔有助於我們幫助你。 –

+0

@theTinMan從現在開始 – JohnDoeYo

回答

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}"} 
+0

如果它來自YAML文件,它與YAML沒有任何關係? – JohnDoeYo

+1

陣列可以來自任何地方。解析YAML沒有任何問題。 – Aetherus

+0

很酷。感謝你的回答! – JohnDoeYo