我的任务是从ruby数据结构中表达如下的YAML结构:
- a
- b
- a
- include:
name: test
- include:
name: test2
我尝试了以下内容:
require "json"
#=> true
require "yaml"
#=> true
array = ["a","b","a","include" => {"name"=>"test"}]
#=> ["a", "b", "a", {"include"=>{"name"=>"test"}}]
puts JSON.parse(array.to_json).to_yaml
#---
#- a
#- b
#- a
#- include:
# name: test
#=> nil
所以这看起来我在正确的轨道上。但是当我只是在数组中添加另一个哈希条目时,我得到以下内容:
array = ["a","b","a","include" => {"name"=>"test"}, "include" => {"name"=>"test2"}]
#(irb):23: warning: duplicated key at line 23 ignored: "include"
#=> ["a", "b", "a", {"include"=>{"name"=>"test2"}}]
puts JSON.parse(array.to_json).to_yaml
#---
#- a
#- b
#- a
#- include:
# name: test2
#=> nil
这让我很困惑。阵列的条目不应该彼此独立吗?为什么Ruby将最后两个条目合并为一个哈希?如果可能的话,我需要做什么来创建具有ruby数据结构的给定YAML结构(如果这是一个愚蠢的问题,我很抱歉,但我是Ruby初学者)?
答案 0 :(得分:2)
尝试在哈希周围添加额外的括号 - 否则Ruby认为它只是数组末尾的一个哈希值。
["a", "b", "a", {"include" => {"name"=>"test"}}, {"include" => {"name"=>"test2"}}].to_yaml