324
array_with_three_elements:
- 1
- 2
- 3

empty_array:

Is there any way to specify that empty_array: is an array with no elements, such as with []? When I load it into a ruby hash I'd like it to know that it's an array.

0

1 Answer 1

522

Try using [], like:

empty_array: []

So in Ruby you have:

x = YAML::load("empty_array: []")
x # => {"empty_array" => []}
Sign up to request clarification or add additional context in comments.

6 Comments

I just wanted to add that you can go into irb and type something like: "require 'yaml'; YAML::dump({ :hi => [] })" to see what the yaml should be for an object.
I'd just like to point out that JSON is an official subset of YAML 1.2 and almost a subset of earlier versions. Thus [] works for an empty sequence, "" works for an empty string, and {} works for an empty mapping.
@DanielH Note that YAML parsers may not support line breaks inside [] or {} structures, which is a major incompatibility with JSON (copy-paste from Wikipedia) Cheers
Many parsers are still on YAML 1.1; this is probably what Wikipedia is talking about. The entire point of the 1.2 release is to make JSON an official subset.
The reason I ended up on this page is that empty_array:[] resulted in a parser error. It apparently only happens in certain contexts. YAML::load("empty_array:[]") works, YAML::load("{empty_array:[]}") fails, and YAML::load("{empty_array: []}") also works. Beware of whitespace in yaml.
|

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.