Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array/Hash to YAML in Ruby on Rails

I want to construct the following YAML formatting from an Array/Hash:

Name:
  gender:
    - female
  nationality:
    - german
    - danish

Right now I have an array like this:

names = ["Abbie", "Abeline", "Abelone"]

What would be the easiest way to get from this array to YAML?

I tried converting it to a hash whilst adding the values for gender and nationality:

names.each do |name|
  (META_HASH ||= Hash.new) = name => { gender: 'female', nationality: ['german', 'danish'] }
end

This, however, just gives me a syntax error. Any help with converting this will be much appreciated!

like image 282
Severin Avatar asked Mar 22 '14 14:03

Severin


1 Answers

> require 'yaml'

> names = ["Abbie", "Abeline", "Abelone"]
=> ["Abbie", "Abeline", "Abelone"]
> puts names.to_yaml
---
- Abbie
- Abeline
- Abelone
=> nil

> h = {:name => { gender: 'female', nationality: ['german', 'danish'] }}
=> {:name=>{:gender=>"female", :nationality=>["german", "danish"]}}
> puts h.to_yaml
---
:name:
  :gender: female
  :nationality:
  - german
  - danish
=> nil

> a = names.map { |n| { n => { gender: 'female', nationality: ['german', 'danish'] } } }
> puts a.to_yaml
---
- Abbie:
    :gender: female
    :nationality:
    - german
    - danish
- Abeline:
    :gender: female
    :nationality:
    - german
    - danish
- Abelone:
    :gender: female
    :nationality:
    - german
    - danish
=> nil
like image 150
Mori Avatar answered Oct 27 '22 13:10

Mori