ruby-on-rails – 在Ruby on Rails中将Array / Hash转换为YAML

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Ruby on Rails中将Array / Hash转换为YAML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从Array / Hash构造以下YAML格式:
Name:
  gender:
    - female
  nationality:
    - german
    - danish

现在我有一个像这样的数组:

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

从这个数组到YAML最简单的方法是什么?

我尝试将其转换为哈希,同时添加性别和国籍的值:

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

但是,这只会给我一个语法错误.任何帮助转换这将非常感谢!

解决方法

> require 'yaml'

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

> h = {:name => { gender: 'female','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','danish'] } } }
> puts a.to_yaml
---
- Abbie:
    :gender: female
    :nationality:
    - german
    - danish
- Abeline:
    :gender: female
    :nationality:
    - german
    - danish
- Abelone:
    :gender: female
    :nationality:
    - german
    - danish
=> nil
原文链接:https://www.f2er.com/ruby/268615.html

猜你在找的Ruby相关文章