Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YAML indentation for array in hash

Tags:

ruby

yaml

I think indentation is important in YAML.

I tested the following in irb:

> puts({1=>[1,2,3]}.to_yaml) ---  1:  - 1 - 2 - 3  => nil  

I expected something like this:

> puts({1=>[1,2,3]}.to_yaml) ---  1:    - 1   - 2   - 3  => nil  

Why isn't there indentation for the array?

I found this at http://www.yaml.org/YAML_for_ruby.html#collections.

The dash in a sequence counts as indentation, so you can add a sequence inside of a mapping without needing spaces as indentation.

like image 629
Sam Kong Avatar asked Jun 09 '13 21:06

Sam Kong


People also ask

How do I specify an array in YAML?

An array is a group of similar values with a single name. In YAML, Array represents a single key mapped to multiple values. Each value starts with a hyphen - symbol followed by space. In a single line, write the same thing above using 'square brackets syntax.

Do indentations matter in YAML?

Indentation. The suggested syntax for YAML files is to use 2 spaces for indentation, but YAML will follow whatever indentation system that the individual file uses. Indentation of two spaces works very well for SLS files given the fact that the data is uniform and not deeply nested.

How string array is defined in YAML?

The block sequence style of YAML uses hyphens or dashes to ( - ) to represent arrays. A hyphen ( - ) followed by white space ( ) represents an element of an array. When you enter the dashes, you need to ensure that all items are at the same indentation level. See the code example below to understand this better.

How do you represent a list in YAML?

All YAML files (regardless of their association with Ansible or not) can optionally begin with --- and end with ... . This is part of the YAML format and indicates the start and end of a document. All members of a list are lines beginning at the same indentation level starting with a "- " (a dash and a space):


2 Answers

Both ways are valid, as far as I can tell:

require 'yaml'  YAML.load(%q{---  1: - 1 - 2 - 3 }) # => {1=>[1, 2, 3]}  YAML.load(%q{---  1:   - 1   - 2   - 3 }) # => {1=>[1, 2, 3]} 

It's not clear why you think there should be spaces before the hyphens. If you think this is a violation of the spec, please explain how.

Why isn't there indentation for the array?

There's no need for indentation before the hyphens, and it's simpler not to add any.

like image 119
Darshan Rivka Whittle Avatar answered Sep 23 '22 05:09

Darshan Rivka Whittle


It's so you can do:

1:  - 2: 3   4: 5 - 6: 7   8: 9 - 10 => {1 => [{2 => 3, 4 => 5}, {6 => 7, 8 => 9}, 10]} 

Basically, dashes delimit objects, and indentation denotes the "value" of the key-value pair.

That's the best I can do; I haven't managed to find any of the reasons behind this or that aspect of the syntax.

like image 44
Narfanator Avatar answered Sep 24 '22 05:09

Narfanator