如何在 ruby​​/rails 中使用 YAML? [英] How do I use YAML in ruby/rails?

查看:40
本文介绍了如何在 ruby​​/rails 中使用 YAML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帐户列表,我想将其另存为 YAML 文件并将其加载到 ruby​​ 中.像这样:

<块引用>

账号1约翰·史密斯史密斯jsmith@gmail.com账户2约翰·多伊jdoejdoe@hotmail.com

然后我想获取名为John Doe"的人的电子邮件地址(例如).

我该怎么做?

解决方案

在这里,你将你的 yaml 对象保存为 Person 对象,然后当你加载它们时,它们会加载到 Person 对象中,使它们更容易处理.

首先将您的 yaml 文件更改为如下所示:

---- !ruby/object:人姓名:约翰·杜姓名:jdoe电子邮件:jdoe@gmail.com- !ruby/object:人姓名:简·多姓名:jdoe电子邮件:jane@hotmail.com

现在您可以将 yaml 文件加载到 Person 对象数组中,然后操作该数组:

FILENAME = 'data.yaml'班级人物attr_accessor :name, :sname, :email结尾需要yaml"# 将返回一个 Person 对象数组.数据 = YAML::load(File.open(FILENAME))# 将打印出数组名称中的第一个对象.#=>约翰·多伊把 data.first.name

I have a list of accounts I want to save as a YAML file and load it into 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).

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.

First change tweak your yaml file to something like this:

--- 
- !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:

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

这篇关于如何在 ruby​​/rails 中使用 YAML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆