开发者

Storing information inside YAML

开发者 https://www.devze.com 2023-01-03 13:41 出处:网络
I looked through the YAML for ruby documentation and couldn\'t find an answer. I have a list of several employees. Each has a name, phone, and email as such:

I looked through the YAML for ruby documentation and couldn't find an answer.

I have a list of several employees. Each has a name, phone, and email as such:

Employees:
    Name | Phone | Email
    john   111     a@b.com
    joe    123     b@a.org
    joan   321     c@a.net

How would I write the above information in YAML to end up with the following ruby output?

employees = [ {:name => 'john', :phone => '111', :email => 'a@b.com'}, {:name => 'joe', :phone => '123', :email => 'b@a.org'}, {:name => 'joan', :phone => '321', :email => 'c@a.net'} ]

This is ho开发者_StackOverflow中文版w I parse the YAML file:

APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")

Thank you!


- name: john
  phone: 111
  email: a@b.com
- name: joe
  phone: 123
  email: b@a.org
- name: joan
  phone: 321
  email: c@a.net

Output is string keys, not symbol keys, but you can make that conversion yourself if really necessary.


Note that standard yaml which ships with Ruby 1.8.6 is NOT UTF / Unicode safe.

Use either Ruby 1.9 yaml or Ya2YAML gem if you'll have any non-ASCII test.

Also, the easiest way to see what the yaml input should be is to create (in Ruby irb), an example of your data structure. Then turn it into yaml text by using the .to_yaml object class method. Eg

require 'yaml'
# create your structure
a = [{'name' => "Larry K", 'age' => 24,
     'job' => {'fulltime' => true, 'name' => 'engineer'}}]
a.to_yaml

=> "--- \n- name: Larry K\n  job: \n    name: engineer\n    fulltime: true\n  age: 24\n"

# then substitute line breaks for the \n:
--- 
- name: Larry K
  job: 
    name: engineer
    fulltime: true
  age: 24
0

精彩评论

暂无评论...
验证码 换一张
取 消