Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/planter/hash.rb
Overview
Hash helpers
Direct Known Subclasses
Instance Method Summary collapse
-
#deep_freeze ⇒ Hash
Freeze all values in a hash.
-
#deep_merge(second) ⇒ Object
Deep merge a hash.
-
#deep_thaw ⇒ Hash
Unfreeze a hash and all nested values.
-
#stringify_keys ⇒ Hash
Turn all keys into string.
-
#stringify_keys! ⇒ Object
Destructive version of #stringify_keys.
-
#symbolize_keys ⇒ Hash
Turn all keys into symbols.
-
#symbolize_keys! ⇒ Hash
Destructive version of #symbolize_keys.
Instance Method Details
#deep_freeze ⇒ Hash
Freeze all values in a hash
77 78 79 80 81 82 83 84 |
# File 'lib/planter/hash.rb', line 77 def deep_freeze chilled = {} each do |k, v| chilled[k] = v.is_a?(Hash) ? v.deep_freeze : v.freeze end chilled.freeze end |
#deep_merge(second) ⇒ Object
Deep merge a hash
57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/planter/hash.rb', line 57 def deep_merge(second) merger = proc do |_, 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 elsif [:undefined, nil, :nil].include?(v2) v1 else v2 end end merge(second.to_h, &merger) end |
#deep_thaw ⇒ Hash
Unfreeze a hash and all nested values
91 92 93 94 95 96 97 98 |
# File 'lib/planter/hash.rb', line 91 def deep_thaw chilled = {} each do |k, v| chilled[k] = v.is_a?(Hash) ? v.deep_thaw : v.dup end chilled.dup end |
#stringify_keys ⇒ Hash
Turn all keys into string
10 11 12 13 14 15 16 17 18 |
# File 'lib/planter/hash.rb', line 10 def stringify_keys each_with_object({}) do |(k, v), hsh| hsh[k.to_s] = if v.is_a?(Hash) || v.is_a?(Array) v.stringify_keys else v end end end |
#stringify_keys! ⇒ Object
Destructive version of #stringify_keys
@return [Hash] Hash with stringified keys
24 25 26 |
# File 'lib/planter/hash.rb', line 24 def stringify_keys! replace stringify_keys end |
#symbolize_keys ⇒ Hash
Turn all keys into symbols
33 34 35 36 37 38 39 40 41 |
# File 'lib/planter/hash.rb', line 33 def symbolize_keys each_with_object({}) do |(k, v), hsh| hsh[k.to_sym] = if v.is_a?(Hash) || v.is_a?(Array) v.symbolize_keys else v end end end |
#symbolize_keys! ⇒ Hash
Destructive version of #symbolize_keys
48 49 50 |
# File 'lib/planter/hash.rb', line 48 def symbolize_keys! replace symbolize_keys end |