-2

My task is to express a YAML structure like the following from ruby data structures:

- a
- b
- a
- include:
    name: test 
- include:
    name: test2

I tried the following:

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

So this looks like I'm on the right track. But when I simply add another hash entry into the array I get the following:

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

This confuses me a lot. Shouldn't the entries of an array be independent of each other? Why does Ruby merge the last two entries together to one hash? And what do I have to do to create the given YAML structure with ruby data structures, if that is possible at all (I'm sorry if that is a stupid question, but I'm a Ruby beginner)?

8
  • 2
    you have duplicate key, which is not allowed.. You need to have uniq names .. You have include twice. Commented Feb 20, 2015 at 18:49
  • I see that ruby thinks I have duplicate keys. But I think it is wrong. The two "include"'s are just two entries in an array, the same as the two "a"'s. But ruby is treating them as if they belong to one hash. That is really confusing. Commented Feb 20, 2015 at 19:17
  • Ohh! okay, I then probably misunderstood. :) Commented Feb 20, 2015 at 19:24
  • Why do people downvote such a question? Commented Feb 20, 2015 at 19:31
  • I don't know.. I didn't.. But not questions, sometime good answers also attacked by some non sense people out there. Don't care them Man! Commented Feb 20, 2015 at 19:34

1 Answer 1

2

Try putting extra braces around your hashes - or else Ruby thinks it's just one hash at the end of the array.

["a", "b", "a", {"include" => {"name"=>"test"}}, {"include" => {"name"=>"test2"}}].to_yaml
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.