Collections in YAML

When you break it all down, YAML is comprised of collections. Collections come in the form of sequences (Arrays) and mappings (Hashes).


Here is an example of a simple sequence:

- dogs
- cats
- badgers
Ex. 1: Simple sequence in YAML

The above sequence is a set of three strings. When you load this YAML document into Ruby, you should receive the following Array:

[ 'dogs', 'cats', 'badgers' ]
Ex. 2: Simple sequence in Ruby

Every Object in Ruby should have a to_yaml method. This method can be called to dump an object into YAML. For example, we can turn the above Array into YAML like so:

require 'yaml'
puts( [ 'dogs', 'cats', 'badgers' ].to_yaml )
# prints:
#   - dogs
#   - cats
#   - badgers
Ex. 3: Using to_yaml to output a sequence

YAML sequences can contain any type of YAML data, including other sequences and mappings. To nest a sequence within another sequence, simply begin a new level of indentation:

  - pineapple
  - coconut
  - umbrella
  - raincoat
Ex. 4: Nested sequence in YAML

Now, let's look at a simple mapping, the other type of collection:

dog: canine
cat: feline
badger: malign
Ex. 5: Simple mapping in YAML

The above mapping is a set of three key/value pairs. In Ruby, this mapping would become a Hash:

{ 'dog' => 'canine',
  'cat' => 'feline',
  'badger' => 'malign' }
Ex. 6: Simple mapping in Ruby

The Hash also has a to_yaml method, which can be used to export a Hash object into YAML:

require 'yaml'
puts( { 'dog' => 'canine',
        'cat' => 'feline',
        'badger' => 'malign' }.to_yaml )
# prints:
#   dog: canine
#   cat: feline
#   badger: malign
Ex. 7: Using to_yaml to output a mapping

Like sequences, mapping values can be any type of object. Mappings can contain nested sequences and mappings.

  age: 22
  sex: M
  age: 24
  sex: F
Ex. 8: Nested mapping

Sequences and mappings may be quite simple, perhaps too simple for much of what you do as a programmer. The advantage to these collections is that they are supported by every YAML implementation. Which means that this data will be available in Python, Perl, Java or any other language which has a YAML library available.

Please refer to the YAML Cookbook [] for more information on collections, including the abbreviated syntax for inline collections.