Skip to content

Instantly share code, notes, and snippets.

@jnstq
Forked from hannestyden/deep_compact.rb
Created March 7, 2020 07:14
Show Gist options
  • Save jnstq/7d8c2cbb7b7fb095bfe624a2ac9fa44f to your computer and use it in GitHub Desktop.
Save jnstq/7d8c2cbb7b7fb095bfe624a2ac9fa44f to your computer and use it in GitHub Desktop.
module DeepCompact
def self.blank?(o)
o.nil? || (o.respond_to?(:empty?) && o.empty?)
end
module Array
def deep_compact
map.with_object(self.class.new) { |e, o|
o << (e.respond_to?(:deep_compact) ? e.deep_compact : e)
}.select { |value| !DeepCompact.blank?(value) }
end
end
module Hash
def deep_compact
map.with_object(self.class.new) { |(k, v), o|
o[k] = v.respond_to?(:deep_compact) ? v.deep_compact : v
}.select { |_, v| !DeepCompact.blank?(v) }
end
end
end
class Array
include DeepCompact::Array
end
class Hash
include DeepCompact::Hash
end
{a: {b: nil}}.deep_compact # => {}
{a: {b: {c: 1, d: nil}}}.deep_compact # => {:a=>{:b=>{:c=>1}}}
{a: {b: {c: 1, d: [{e: []}]}}}.deep_compact # => {:a=>{:b=>{:c=>1}}}
{a: {b: {c: 1, d: [{e: []}, {f: ""}, 1, nil, {}]}}}.deep_compact # => {:a=>{:b=>{:c=>1, :d=>[1]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment