YAML list

YAML is a fairly common and very readable key/ value notation. YAML files can also be used to map lists.

YAML lists

A simple example of a YAML list:

# languages.yml
  - Ruby
  - JavaScript
  - Elixir

The YAML parser generates arrays according to the lists:

# => ["Ruby", "JavaScript", "Elixir"]

In the case of short list elements, the abbreviated notation looks like:

# languages.yml
languages: [Ruby, JavaScript, Elixir]
# => ["Ruby", "JavaScript", "Elixir"]

Lists of key/ value pairs

Likkewise key/ value pairs can be mapped as lists:

    name: Ruby
    version: 2.3.0
    name: Python
    version: 2.7.3

The parser creates an Array of Hashes:

[{"name"=>"Ruby", "version"=>"2.3.0"}, {"name"=>"Python", "version"=>"2.7.3"}]

Nested lists

Nested lists Nested lists are also possible. For example, as a source for a table could look like:

  - [Typing    , Name, Version]
  - [dynamic, Ruby  , 2.3.0    ]
  - [static      , Java    , 1.8.0    ]

The result is an Array of Arrays:

[["Typisierung", "Name", "Version"], ["Dynamisch", "Ruby", "2.3.0"], ["Statisch", "Java", "1.8.0"]]

A Ruby on Rails use case

Of course, there are different use cases for YAML sources, e.g. the I18n (Internationalization) of Ruby on Rail’s projects. Views can take advantage of pre-formatted YAML lists:

# config/locales/features/de.yml
    - Dynamic typing
    - Duck typing
    - Closures

In the view, the translated Strings can be iterated conveniently:

  - I18n.t('features').each |feature|
    %li= feature

The corresponding HTML:

<ul class="features">
  <li>Dynamic typing</li>
  <li>Duck typing</li>