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
languages:
- Ruby
- JavaScript
- Elixir
The YAML parser generates arrays according to the lists:
YAML.load_file('languages.yml')['languages']
# => ["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:
languages:
-
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:
languages:
- [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
en:
features:
- Dynamic typing
- Duck typing
- Closures
In the view, the translated Strings can be iterated conveniently:
%ul.features
- I18n.t('features').each |feature|
%li= feature
The corresponding HTML:
<ul class="features">
<li>Dynamic typing</li>
<li>Duck typing</li>
<li>Closures</li>
</ul>