如何在ruby / rails中使用YAML?
我有一个帐户列表,我想保存为YAML文件并将其加载到ruby中。 像这样的东西:
Account1 John Smith jsmith jsmith@gmail.com Account2 John Doe jdoe jdoe@hotmail.com
然后我想获得名为“John Doe”的人的电子邮件地址(例如)。
我该怎么做呢?
在这里,您将yaml对象保存为Person对象,然后在加载它们时,它们将加载到Person对象中,使它们更容易处理。
首先将你的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
现在,您可以将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
在文件顶部require yaml
。
执行此操作时,对象将获得to_yaml
方法。 加载yaml文件很容易..请参阅此处的文档。 http://yaml4r.sourceforge.net/doc/