2010-10-23 34 views

回答

9

在这里,您将yaml对象保存为Person对象,然后当您将它们加载回来时,它们将加载到Person对象中,使它们更容易处理。

首先变化调整你的YAML文件是这样的:

--- 
- !ruby/object:Person 
    name: John Doe 
    sname: jdoe 
    email: [email protected] 
- !ruby/object:Person 
    name: Jane Doe 
    sname: jdoe 
    email: [email protected] 

现在,您可以YAML文件加载到Person对象的数组,然后操作数组:

FILENAME = 'data.yaml' 

class Person 
attr_accessor :name, :sname, :email 
end 

require "yaml" 
# Will return an array of Person objects. 
data = YAML::load(File.open(FILENAME)) 

# Will print out the first object in the array's name. #=> John Doe 
puts data.first.name 
1

你只是在文件顶部说require yaml

当您这样做时,对象会得到一个to_yaml方法。加载yaml文件很容易。请参阅这里的文档。 http://yaml4r.sourceforge.net/doc/