Created
September 25, 2024 14:02
-
-
Save SofiaSousa/747d641595c5f89a8044fddbe80ee389 to your computer and use it in GitHub Desktop.
Ruby Hash `deep_compact` and `deep_compact!`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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