JohnDoeYo JohnDoeYo - 4 months ago 11
Ruby Question

Output all values of a yaml file key with formatting

I have a yaml file that has multiple values for a couple of keys:

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 file '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


What I want to do is output all those keys with some sort of formatting, for example when this is run:

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>


The expected output of this would be:

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


How can I go about outputting the information inside the array with numbers to match IF there is more than one value?

Answer

Your question has nothing to do with YAML at all. It's all about how to print out an array with index.

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

or

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