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 ⇒ Hash
Turn all keys and values into string.
-
#stringify! ⇒ Hash
Destructive version of #stringify.
-
#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
101 102 103 104 105 106 107 108 |
# File 'lib/planter/hash.rb', line 101 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
81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/planter/hash.rb', line 81 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
115 116 117 118 119 120 121 122 |
# File 'lib/planter/hash.rb', line 115 def deep_thaw chilled = {} each do |k, v| chilled[k] = v.is_a?(Hash) ? v.deep_thaw : v.dup end chilled.dup end |
#stringify ⇒ Hash
Turn all keys and values into string
10 11 12 13 14 15 16 17 18 |
# File 'lib/planter/hash.rb', line 10 def stringify each_with_object({}) do |(k, v), hsh| hsh[k.to_s] = if v.is_a?(Hash) || v.is_a?(Array) v.stringify else v.to_s end end end |
#stringify! ⇒ Hash
Destructive version of #stringify
26 27 28 |
# File 'lib/planter/hash.rb', line 26 def stringify! replace stringify end |
#stringify_keys ⇒ Hash
Turn all keys into string
34 35 36 37 38 39 40 41 42 |
# File 'lib/planter/hash.rb', line 34 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
48 49 50 |
# File 'lib/planter/hash.rb', line 48 def stringify_keys! replace stringify_keys end |
#symbolize_keys ⇒ Hash
Turn all keys into symbols
57 58 59 60 61 62 63 64 65 |
# File 'lib/planter/hash.rb', line 57 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
72 73 74 |
# File 'lib/planter/hash.rb', line 72 def symbolize_keys! replace symbolize_keys end |