我有一个我想保存为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/