我正在尝试执行以下操作:
和代码:
yml_string = Psych.dump(File.read(infile))
Psych.load_stream(yml_string) .each do |mobj|
puts "mobj:\n #{mobj}"
end
puts会打印yml_string的内容(多个yaml文档),但它是一个长字符串。如何从yml_string解析每个yaml doc并将它们存储到ruby对象中?
infile的内容(根据OP的评论):
---
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
答案 0 :(得分:1)
这就是我最终的结果
yaml_hash = Psych.load_stream(File.read(infile))
yaml_hash.each do |member|
mem = Hash[member['member']]
end
感谢您的帮助。
答案 1 :(得分:0)
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"}}]
最近的MRI心理与yaml lib相同
p [RUBY_VERSION, YAML == Psych]
["2.0.0", true]
p [RUBY_VERSION, YAML == Psych]
["1.9.3", true]