Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/rcore_ext/array/compact.rb

Instance Method Summary collapse

Instance Method Details

#deep_compactObject

Returns a copy of self with all nil, empty and blank nested elements removed.

[1, 2, nil, [3, 4, nil, [5, nil], []], {}].deep_compact   #=> [1, 2, [3, 4, [5]]]
[1, 2].deep_compact         #=> [1, 2]
[1, 2, ['']].deep_compact   #=> [1, 2]
[1, 2, ['  ']].deep_compact #=> [1, 2]


11
12
13
14
# File 'lib/rcore_ext/array/compact.rb', line 11

def deep_compact
  result = dup.deep_compact!
  result.nil? ? self : result
end

#deep_compact!Object

Removes nil, empty and blank nested elements from the array. Returns nil if no changes were made, otherwise returns array.

[1, 2, nil, [3, 4, nil, [5, nil], []], {}].deep_compact!   #=> [1, 2, [3, 4, [5]]]
[1, 2].deep_compact!         #=> nil
[1, 2, ['']].deep_compact!   #=> [1, 2]
[1, 2, ['  ']].deep_compact! #=> [1, 2]


23
24
25
26
27
28
29
30
31
32
# File 'lib/rcore_ext/array/compact.rb', line 23

def deep_compact!
  index = 0; changed = false
  while size > index
    item = at(index)
    (changed = true unless item.deep_compact!.nil?) if item.is_a?(Array)
    (self.delete_at(index); changed = true; next) if item.blank? 
    index += 1
  end
  changed ? self : nil
end