user3429034
user3429034

Reputation: 11

Ruby > Psych -> How to parse yaml docs in to ruby objects

I'm trying to do the following:

and the code:

yml_string = Psych.dump(File.read(infile))
Psych.load_stream(yml_string) .each do |mobj|
  puts "mobj:\n #{mobj}"
end

The puts prints the contents of the yml_string (multiple yaml docs) but it is one long string. How does one go about parsing each yaml doc from the yml_string and store them in to ruby objects?

The contents of infile (based on OP's comment):

---
member:
    country: AF
    phone1: 60 223-4564
    phone2: +93 799 123-456

---
member:
    country: BR
    phone1: +55 55 2000 3456
    phone2: 55 9000 1234

---
member:
    country: CA
    phone1: 604 423-4567
    phone2: +1 604 423-4567

Upvotes: 0

Views: 929

Answers (2)

user3429034
user3429034

Reputation: 11

This is what I ended up with

yaml_hash = Psych.load_stream(File.read(infile))
yaml_hash.each do |member|
  mem = Hash[member['member']]
end

Thank you for all your help.

Upvotes: 1

avsej
avsej

Reputation: 3962

require 'yaml'
require 'pp'

infile = "test.yml"

pp YAML.load_stream(File.read(infile))
# [{"member"=>
#    {"country"=>"AF", "phone1"=>"60 223-4564", "phone2"=>"+93 799 123-456"}},
#  {"member"=>
#    {"country"=>"BR", "phone1"=>"+55 55 2000 3456", "phone2"=>"55 9000 1234"}},
#  {"member"=>
#    {"country"=>"CA", "phone1"=>"604 423-4567", "phone2"=>"+1 604 423-4567"}}]

On recent MRI psych is the same as yaml lib

p [RUBY_VERSION, YAML == Psych]
["2.0.0", true]
p [RUBY_VERSION, YAML == Psych]
["1.9.3", true]

Upvotes: 0

Related Questions