Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/na/hash.rb
Overview
Extensions to Ruby’s Hash class for symbolizing keys and deep freezing values.
Direct Known Subclasses
Instance Method Summary collapse
-
#deep_freeze ⇒ Object
Freeze all values in a hash.
-
#deep_freeze! ⇒ Hash
Freeze all values in a hash in place.
-
#deep_merge(second) ⇒ Hash
Recursively merge two hashes, combining arrays and preferring non-nil values.
-
#deep_thaw ⇒ Hash
Recursively duplicate all values in a hash.
-
#deep_thaw! ⇒ Hash
Recursively duplicate all values in a hash in place.
-
#symbolize_keys ⇒ Hash
Convert all keys in the hash to symbols recursively.
Instance Method Details
#deep_freeze ⇒ Object
Freeze all values in a hash
24 25 26 27 28 29 30 31 |
# File 'lib/na/hash.rb', line 24 def deep_freeze chilled = {} each do |k, v| chilled[k] = v.is_a?(Hash) ? v.deep_freeze : v.freeze end chilled.freeze end |
#deep_freeze! ⇒ Hash
Freeze all values in a hash in place
36 37 38 |
# File 'lib/na/hash.rb', line 36 def deep_freeze! replace deep_thaw.deep_freeze end |
#deep_merge(second) ⇒ Hash
Recursively merge two hashes, combining arrays and preferring non-nil values
63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/na/hash.rb', line 63 def deep_merge(second) merger = proc { |_, v1, v2| if v1.is_a?(Hash) && v2.is_a?(Hash) v1.merge(v2, &merger) elsif v1.is_a?(Array) && v2.is_a?(Array) v1 | v2 else [:undefined, nil, :nil].include?(v2) ? v1 : v2 end } merge(second.to_h, &merger) end |
#deep_thaw ⇒ Hash
Recursively duplicate all values in a hash
43 44 45 46 47 48 49 50 |
# File 'lib/na/hash.rb', line 43 def deep_thaw chilled = {} each do |k, v| chilled[k] = v.is_a?(Hash) ? v.deep_thaw : v.dup end chilled.dup end |
#deep_thaw! ⇒ Hash
Recursively duplicate all values in a hash in place
55 56 57 |
# File 'lib/na/hash.rb', line 55 def deep_thaw! replace deep_thaw end |