views:

57

answers:

2

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     [email protected]
    joe    123     [email protected]
    joan   321     [email protected]

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

employees = [ {:name => 'john', :phone => '111', :email => '[email protected]'}, {:name => 'joe', :phone => '123', :email => '[email protected]'}, {:name => 'joan', :phone => '321', :email => '[email protected]'} ]

This is how I parse the YAML file:

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

Thank you!

+2  A: 
- name: john
  phone: 111
  email: [email protected]
- name: joe
  phone: 123
  email: [email protected]
- name: joan
  phone: 321
  email: [email protected]

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

Matchu
do I put those dashes in?
yuval
Also, I need it to be nested under `APP_CONFIG['employees']` - would I indent everything by two spaces?
yuval
Yes to both questions.
Tom
+1  A: 

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
Larry K
or just say `puts a.to_yaml` and copy)
averell