Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/doing/hash.rb
Overview
Hash helpers
Instance Method Summary collapse
-
#deep_freeze ⇒ description_of_the_return_value
Freeze all values in a hash.
- #deep_freeze! ⇒ Object
-
#deep_set(path, value) ⇒ Object
Set a nested hash value using an array.
-
#stringify_keys ⇒ Object
Turn all keys into string.
-
#symbolize_keys ⇒ Object
Turn all keys into symbols.
Instance Method Details
#deep_freeze ⇒ description_of_the_return_value
Freeze all values in a hash
11 12 13 |
# File 'lib/doing/hash.rb', line 11 def deep_freeze map { |k, v| v.is_a?(Hash) ? v.deep_freeze : v.freeze }.freeze end |
#deep_freeze! ⇒ Object
15 16 17 |
# File 'lib/doing/hash.rb', line 15 def deep_freeze! replace deep_freeze end |
#deep_set(path, value) ⇒ Object
Set a nested hash value using an array
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/doing/hash.rb', line 39 def deep_set(path, value) if path.count == 1 if value self[path[0]] = value else delete(path[0]) end else if value self.default_proc = ->(h, k) { h[k] = Hash.new(&h.default_proc) } dig(*path[0..-2])[path.fetch(-1)] = value else return self unless dig(*path) dig(*path[0..-2]).delete(path.fetch(-1)) path.pop cleaned = self path.each do |key| if cleaned[key].empty? cleaned.delete(key) break end cleaned = cleaned[key] end empty? ? nil : self end end end |
#stringify_keys ⇒ Object
Turn all keys into string
Return a copy of the hash where all its keys are strings
22 23 24 |
# File 'lib/doing/hash.rb', line 22 def stringify_keys each_with_object({}) { |(k, v), hsh| hsh[k.to_s] = v.is_a?(Hash) ? v.stringify_keys : v } end |
#symbolize_keys ⇒ Object
Turn all keys into symbols
27 28 29 |
# File 'lib/doing/hash.rb', line 27 def symbolize_keys each_with_object({}) { |(k, v), hsh| hsh[k.to_sym] = v.is_a?(Hash) ? v.symbolize_keys : v } end |