Search code examples
yaml

YAML indentation for array in hash


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.


Solution

  • 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.