[英]How do I use YAML in ruby/rails?
I have a list of accounts I want to save as a YAML file and load it into ruby. 我有一个帐户列表,我想保存为YAML文件并将其加载到ruby中。 Something like this:
像这样的东西:
Account1 John Smith jsmith jsmith@gmail.com Account2 John Doe jdoe jdoe@hotmail.com
Then I want to get the email address of the person with the name of "John Doe" (for example). 然后我想获得名为“John Doe”的人的电子邮件地址(例如)。
How do I do this? 我该怎么做呢?
Here, you save your yaml objects as Person objects and then when you load them back, they will load into Person objects, making them a lot easier to handle. 在这里,您将yaml对象保存为Person对象,然后在加载它们时,它们将加载到Person对象中,使它们更容易处理。
First change tweak your yaml file to something like this: 首先将你的yaml文件调整为这样的:
---
- !ruby/object:Person
name: John Doe
sname: jdoe
email: jdoe@gmail.com
- !ruby/object:Person
name: Jane Doe
sname: jdoe
email: jane@hotmail.com
Now you can load your yaml file into an array of Person objects and then manipulate the array: 现在,您可以将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
You just say require yaml
at the top of your file. 你只
require yaml
在文件顶部require yaml
。
Objects get a to_yaml
method when you do this. 执行此操作时,对象将获得
to_yaml
方法。 Loading of yaml files is easy to.. Refer to the docs here. 加载yaml文件很容易..请参阅此处的文档。 http://yaml4r.sourceforge.net/doc/
http://yaml4r.sourceforge.net/doc/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.