我有一個我想保存爲YAML文件並加載到ruby的帳戶列表。事情是這樣的:如何在ruby/rails中使用YAML?
Account1 John Smith jsmith [email protected] Account2 John Doe jdoe [email protected]
然後我想用「李四」(例如)的名稱來獲取用戶的電子郵件地址。
我該怎麼做?
我有一個我想保存爲YAML文件並加載到ruby的帳戶列表。事情是這樣的:如何在ruby/rails中使用YAML?
Account1 John Smith jsmith [email protected] Account2 John Doe jdoe [email protected]
然後我想用「李四」(例如)的名稱來獲取用戶的電子郵件地址。
我該怎麼做?
在這裏,您將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
你只是在文件頂部說require yaml
。
當您這樣做時,對象會得到一個to_yaml
方法。加載yaml文件很容易。請參閱這裏的文檔。 http://yaml4r.sourceforge.net/doc/