Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/qat/core_ext/object/deep_compact.rb

Overview

class Hash

Instance Method Summary collapse

Instance Method Details

#deep_compactHash

Returns a copy of the current hash with non nil values throughout all tree

Examples:

> hash = {a: nil, b: 'b'}
> hash.deep_compact
=> {b: 'b'}
> hash
=> {a: nil, b: 'b'}

> hash = { a: nil, b: { ba: 'ba', bb: { bba: nil, bbb: 'bbb' }, bc: nil } }
> hash.deep_compact
=> { b: { ba: 'ba', bb: { bbb: 'bbb' } } }
> hash
=> { a: nil, b: { ba: 'ba', bb: { bba: nil, bbb: 'bbb' }, bc: nil } }

> hash = { a: nil, b: 'value', c: [1, 2, 3] }
> hash.deep_compact
=> { b: 'value', c: [1, 2, 3] }
> hash
=> { a: nil, b: 'value', c: [1, 2, 3] }

> hash = { a: nil, b: 'value', c: [1, nil, { ca: 3, cb: nil }] }
> hash.deep_compact
=> { b: 'value', c: [1, { ca: 3 }] }
> hash
=> { a: nil, b: 'value', c: [1, nil, { ca: 3, cb: nil }] }

Returns:



34
35
36
# File 'lib/qat/core_ext/object/deep_compact.rb', line 34

def deep_compact
  deep_dup.deep_compact!
end

#deep_compact!Hash

Replaces the current hash with non nil values throughout all tree

Examples:

> hash = {a: nil, b: 'b'}
> hash.deep_compact!
=> {b: 'b'}
> hash
=> {b: 'b'}

> hash = { a: nil, b: { ba: 'ba', bb: { bba: nil, bbb: 'bbb' }, bc: nil } }
> hash.deep_compact!
=> { b: { ba: 'ba', bb: { bbb: 'bbb' } } }
> hash
=> { b: { ba: 'ba', bb: { bbb: 'bbb' } } }

> hash = { a: nil, b: 'value', c: [1, 2, 3] }
> hash.deep_compact!
=> { b: 'value', c: [1, 2, 3] }
> hash
=> { b: 'value', c: [1, 2, 3] }

> hash = { a: nil, b: 'value', c: [1, nil, { ca: 3, cb: nil }] }
> hash.deep_compact!
=> { b: 'value', c: [1, { ca: 3 }] }
> hash
=> { b: 'value', c: [1, { ca: 3 }] }

Returns:



67
68
69
70
71
72
# File 'lib/qat/core_ext/object/deep_compact.rb', line 67

def deep_compact!
  self.compact!
  self.each do |key, value|
    self[key] = value.respond_to?(:deep_compact!) ? value.deep_compact! : value
  end
end