How to use YAML in ruby ​​/ rails?

I have a list of accounts that I want to save as a YAML file, and upload it to ruby. Something like that:

Account1 John Smith jsmith jsmith@gmail.com Account2 John Doe jdoe jdoe@hotmail.com 

Then I want to get the email address of a person named "John Doe" (for example).

How to do it?

+4
source share
2 answers

Here you save yaml objects as Person objects, and then when you load them back, they will be loaded into Person objects, which simplifies their handling.

The first change will change 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 name. #=> John Doe puts data.first.name 
+9
source

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

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

+1
source

All Articles