Module: HashHelper::DeepNormalize

Included in:
Hash
Defined in:
lib/hash_helper/deep_normalize.rb

Instance Method Summary collapse

Instance Method Details

#deep_normalize(default_value: nil) ⇒ Hash

Recursively normalizes the hash by merging it with a default structure.

This method creates a nested default structure based on the keys of the hash, assigning each key a specified default value. The resulting structure is then deeply merged with the original hash.

Examples:

Normalize a hash with default values

hash = { a: { x: 1, y: 2 }, b: { z: 3 } }
hash.extend(HashHelper::DeepNormalize)
normalized = hash.deep_normalize(default_value: 0)
# Result: { a: { x: 1, y: 2, z: 0 }, b: { x: 0, y: 0, z: 3 } }

Parameters:

  • default_value (Object) (defaults to: nil)

    The value to assign as the default for all keys in the normalized structure. Defaults to ‘nil`.

Returns:

  • (Hash)

    A new hash that combines the default structure and the original hash.



20
21
22
# File 'lib/hash_helper/deep_normalize.rb', line 20

def deep_normalize(default_value: nil)
  build_default(self, default_value: default_value).deep_merge(self)
end