Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/ds_hash/hash_core_ext.rb
Instance Method Summary collapse
- #clean ⇒ Object (also: #compact)
- #clean! ⇒ Object (also: #compact!)
- #deep_fetch(*keys) ⇒ Object
- #deep_key?(*keys) ⇒ Boolean
- #to_struct ⇒ Object
Instance Method Details
#clean ⇒ Object Also known as: compact
35 36 37 38 |
# File 'lib/ds_hash/hash_core_ext.rb', line 35 def clean hsh = self.deep_dup hsh.clean! end |
#clean! ⇒ Object Also known as: compact!
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/ds_hash/hash_core_ext.rb', line 20 def clean! swoop = Proc.new { |k, v| if v.respond_to? 'clean!' v.clean! false elsif v.respond_to? 'compact!' v.compact! false else v.to_s.empty? end } delete_if &swoop end |
#deep_fetch(*keys) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/ds_hash/hash_core_ext.rb', line 55 def deep_fetch *keys def_value = keys.pop unless keys[keys.size-1].is_a? Symbol key = keys.shift if !key.is_a? Symbol return nil elsif keys.empty? if block_given? ret = yield self[key] || {} else ret = self[key] end elsif self[key].is_a? Hash ret = self[key].deep_fetch(*keys) end ret == nil ? def_value : ret end |
#deep_key?(*keys) ⇒ Boolean
46 47 48 49 50 51 |
# File 'lib/ds_hash/hash_core_ext.rb', line 46 def deep_key? *keys key = keys.shift return key?(key) if keys.empty? return self[key].deep_key?(*keys) if self[key].is_a? Hash false end |
#to_struct ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/ds_hash/hash_core_ext.rb', line 74 def to_struct hash = self klass = Struct.new(*hash.keys.map(&:to_sym) ) struct = klass.new(*hash.values) hash.each do |key, value| if value.is_a?(Hash) v = value.to_struct struct[key] = v end end return struct end |