Skip to content

Instantly share code, notes, and snippets.

@SofiaSousa
Created September 25, 2024 14:02
Show Gist options
  • Save SofiaSousa/747d641595c5f89a8044fddbe80ee389 to your computer and use it in GitHub Desktop.
Save SofiaSousa/747d641595c5f89a8044fddbe80ee389 to your computer and use it in GitHub Desktop.
Ruby Hash `deep_compact` and `deep_compact!`
class Hash
# Returns a new hash with the nil values/key pairs removed recursively.
#
# hash = { a: true, b: { c: [1, 2, 3], d: { e: nil, f: 4 } }, g: nil }
#
# hash.deep_compact # => { a: true, b: { c: [1, 2, 3], d: { f: 4 } } }
def deep_compact
dup.deep_compact!
end
# Same as +deep_compact+, but modifies +self+.
def deep_compact!
# `compact!` Returns nil if no changes were made, otherwise returns the hash.
# When nil, old hash is rescued.
hash = self
(compact! || hash).each do |key, value|
self[key] = value.is_a?(Hash) ? value.deep_compact : value
end
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment