Skip to content

Instantly share code, notes, and snippets.

@3limin4t0r 3limin4t0r/#ruby-201909091908.rb Secret
Last active Sep 9, 2019

Embed
What would you like to do?
module DeepDup
module Object
alias deep_dup dup
end
module List
def deep_dup
dup.tap { |list| list.map!(&:deep_dup) }
end
end
module Dict
def deep_dup
dup.tap { |dict| dict.transform_values!(&:deep_dup) }
end
end
end
Object.include(DeepDup::Object)
Array.include(DeepDup::List)
Hash.include(DeepDup::Dict)
module DeepCompact
module Common
def deep_compact
deep_dup.deep_compact!
end
end
module List
include Common
def deep_compact!
each { |value| value.deep_compact! if value.respond_to?(:deep_compact!) }
.delete_if { |value| value.nil? || value.respond_to?(:empty?) && value.empty? }
end
end
module Dict
include Common
def deep_compact!
each_value { |value| value.deep_compact! if value.respond_to?(:deep_compact!) }
.delete_if { |_key, value| value.nil? || value.respond_to?(:empty?) && value.empty? }
end
end
end
Array.include(DeepCompact::List)
Hash.include(DeepCompact::Dict)
x = [{a: 1, b: [2, 3, nil], c: [], d: {a: nil}}, 1, 2, [], [1, 2, 3], [nil, nil, []]]
x.deep_compact #=> [{:a=>1, :b=>[2, 3]}, 1, 2, [1, 2, 3]]
x #=> [{:a=>1, :b=>[2, 3, nil], :c=>[], :d=>{:a=>nil}}, 1, 2, [], [1, 2, 3], [nil, nil, []]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.