Module: YamlNormalizer::Ext::Nested

Defined in:
lib/yaml_normalizer/ext/nested.rb

Overview

YamlNormalizer::Ext::Nested extends instances of Hash to provide the additional public helper method nested. The approach of extending Hash instances avoids monkey-patching a Ruby Core class and using refinements.

Instance Method Summary collapse

Instance Method Details

#nestedHash

Transforms a flat key-value pair Hash into a tree-shaped Hash, assuming tree levels are separated by a dot. nested does not modify the instance of Hash it’s called on.

Examples:

hash = {'a.b.c' => 1, 'b.x' => 2, 'b.y.ok' => true, 'b.z' => 4}
hash.extend(YamlNormalizer::Ext::Nested)
hash.nested
=> {"a"=>{"b"=>{"c"=>1}}, "b"=>{"x"=>2, "y"=>{"ok"=>true}, "z"=>4}}

Returns:

  • (Hash)

    tree-shaped Hash



19
20
21
22
23
# File 'lib/yaml_normalizer/ext/nested.rb', line 19

def nested
  tree = {}
  each { |key, val| nest_key(tree, key, val) }
  tree
end