Skip to content

Instantly share code, notes, and snippets.

@hannestyden
Created August 5, 2014 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hannestyden/b3c1f5619a7f801e3037 to your computer and use it in GitHub Desktop.
Save hannestyden/b3c1f5619a7f801e3037 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]}}}
@hannestyden
Copy link
Author

Maybe it should be called DeepHardCompact since it rejects "blank" (nil | empty) values ...

@toto
Copy link

toto commented Dec 12, 2014

Googling deep_compact I found this. Kudos Google.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment