Class: Yes::Core::Utils::HashUtils
- Inherits:
-
Object
- Object
- Yes::Core::Utils::HashUtils
- Defined in:
- lib/yes/core/utils/hash_utils.rb
Overview
Utility class for deep hash operations
Class Method Summary collapse
-
.deep_dup(hash) ⇒ Hash, Object
Returns a deep duplicate of a hash, recursively duplicating nested hashes.
-
.deep_flatten_hash(obj, prefix = nil, memo = {}) ⇒ Hash
Returns a hash with the keys flattened.
Class Method Details
.deep_dup(hash) ⇒ Hash, Object
Returns a deep duplicate of a hash, recursively duplicating nested hashes.
17 18 19 20 21 22 23 |
# File 'lib/yes/core/utils/hash_utils.rb', line 17 def deep_dup(hash) return hash unless hash.instance_of?(Hash) dupl = hash.dup dupl.each { |k, v| dupl[k] = v.instance_of?(Hash) ? deep_dup(v) : v } dupl end |
.deep_flatten_hash(obj, prefix = nil, memo = {}) ⇒ Hash
Returns a hash with the keys flattened. Scalar, nested-hash and
array values all honour the prefix consistently.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/yes/core/utils/hash_utils.rb', line 40 def deep_flatten_hash(obj, prefix = nil, memo = {}) case obj when Hash obj.each do |key, value| case [key, value] in Hash, Array memo[deep_flatten_hash(key)] = memo[deep_flatten_hash(value)] in String | Symbol, Hash deep_flatten_hash(value, prefix ? "#{prefix}.#{key}" : key.to_s, memo) in String | Symbol, Array memo[prefix ? "#{prefix}.#{key}" : key.to_s] = deep_flatten_hash(value) in Array, _ memo[deep_flatten_hash(key)] = deep_flatten_hash(value) else memo[prefix ? "#{prefix}.#{key}" : key.to_s] = value end end memo when Array obj.map { deep_flatten_hash(_1) } else obj end end |