简体   繁体   中英

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. 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

You just say require yaml at the top of your file.

Objects get a to_yaml method when you do this. Loading of yaml files is easy to.. Refer to the docs here. http://yaml4r.sourceforge.net/doc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM