Module: HashHelper::DeepInvert

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

Instance Method Summary collapse

Instance Method Details

#deep_invertHash

Deeply inverts a hash, creating a new structure where the values in the original hash are moved outward, and the keys are reversed in the nesting.

Examples:

Deeply invert a nested hash

hash = { a: { b: { c: 1 } }, d: { e: 2 } }
hash.extend(HashHelper::DeepInvert)
inverted = hash.deep_invert
# Result: { c: { b: { a: 1 } }, e: { d: 2 } }

Returns:

  • (Hash)

    A new hash with the keys and values deeply inverted.



13
14
15
16
17
# File 'lib/hash_helper/deep_invert.rb', line 13

def deep_invert
  each_with_object({}) do |(outer_key, outer_value), result|
    traverse_and_invert(outer_value, [outer_key], result)
  end
end