2

I have a machine.yml file as follows:

---
    machines:  
     A:
        ip: ABC
        pass: vass
        user: A

     B:
        ip: XYZ
        pass: grass
        user: B

     C:
        ip: klm
        pass: pass
        user: C

I tried to parse the above file as follows:

        machines = YAML.load_file('machine.yml')
        machines = machines['machines']
        ## Iterate through entries in YAML file
        machines.each_value do |machines| 
           var = [machines["A"]["ip"], machines["A"]["pass"], machines["B"]["ip"],machines["B"]["pass"], machines["C"]["ip"],machines["C"]["pass"]]
           # var should have all the values 
        end

The "var" should contain all the values as a string. But I am not able execute the above piece as it's throwing errors. How can I parse all the values of YAML separately?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Learner
  • 453
  • 13
  • 29

1 Answers1

6

Your code

Since you hardcode the keys you're interested in, you don't need to iterate with each_values :

machines = YAML.load_file('machine.yml')
machines = machines['machines']
var = [machines["A"]["ip"], machines["A"]["pass"], machines["B"]["ip"],machines["B"]["pass"], machines["C"]["ip"],machines["C"]["pass"]]

Alternative

First, you should try not to override the same variable every time (machines). It's called "shadowing", and it makes it harder to understand and use your code.

Depending on what you want to do, each, map or flat_map could help you :

require 'yaml'

yaml_hash = YAML.load_file('machine.yml')
p yaml_hash['machines']
#=> {"A"=>{"ip"=>"ABC", "pass"=>"vass", "user"=>"A"}, "B"=>{"ip"=>"XYZ", "pass"=>"grass", "user"=>"B"}, "C"=>{"ip"=>"klm", "pass"=>"pass", "user"=>"C"}}

yaml_hash['machines'].each do |letter, hash|
  p letter
  p hash['ip']
  p hash['pass']
end

#=>
# "A"
# "ABC"
# "vass"
# "B"
# "XYZ"
# "grass"
# "C"
# "klm"
# "pass"

p yaml_hash['machines'].values
#=> [{"ip"=>"ABC", "pass"=>"vass", "user"=>"A"}, {"ip"=>"XYZ", "pass"=>"grass", "user"=>"B"}, {"ip"=>"klm", "pass"=>"pass", "user"=>"C"}]

p yaml_hash['machines'].values.map { |hash| hash.values_at('ip', 'pass') }
#=> ["ABC", "vass"], ["XYZ", "grass"], ["klm", "pass"]]

p yaml_hash['machines'].values.flat_map { |hash| hash.values_at('ip', 'pass') }
#=> ["ABC", "vass", "XYZ", "grass", "klm", "pass"]
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • how to pass each value to a bash script i am doing as sample.sh, : args=>[p hash['ip']] but its not working. – Learner Jan 23 '17 at 12:38