Class: Array

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

Overview

class Array

Instance Method Summary collapse

Instance Method Details

#deep_compactArray

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

Examples:

> array = [nil, 'b']
> array.deep_compact!
=> ['b']
> array
=> [nil, 'b']

> array = [nil, ['ba', [nil, 'bbb'], nil], 'c']
> array.deep_compact!
=> [['ba', ['bbb']], 'c']
> array
=> [nil, ['ba', [nil, 'bbb'], nil], 'c']

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

> array = [nil, 'value', { c: [1, nil, { d: 3, e: nil }] }]
> array.deep_compact!
=> ['value', { c: [1, { d: 3 }] }]
> array
=> [nil, 'value', { c: [1, nil, { d: 3, e: nil }] }]

Returns:



105
106
107
# File 'lib/qat/core_ext/object/deep_compact.rb', line 105

def deep_compact
  deep_dup.deep_compact!
end

#deep_compact!Array

Replaces the current array with non nil values throughout all tree

Examples:

> array = [nil, 'b']
> array.deep_compact!
=> ['b']
> array
=> ['b']

> array = [nil, ['ba', [nil, 'bbb'], nil], 'c']
> array.deep_compact!
=> [['ba', ['bbb']], 'c']
> array
=> [['ba', ['bbb']], 'c']

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

> array = [nil, 'value', { c: [1, nil, { d: 3, e: nil }] }]
> array.deep_compact!
=> ['value', { c: [1, { d: 3 }] }]
> array
=> ['value', { c: [1, { d: 3 }] }]

Returns:



138
139
140
141
142
143
# File 'lib/qat/core_ext/object/deep_compact.rb', line 138

def deep_compact!
  self.compact!
  self.map! do |element|
    element.respond_to?(:deep_compact!) ? element.deep_compact! : element
  end
end