2010-10-23 28 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/