Last active
September 28, 2018 08:28
-
-
Save StanBoyet/a76fb58affff4ceca5120dc495714824 to your computer and use it in GitHub Desktop.
Recursively replace a value `initial` by `replacement`
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
def denilize(h, initial, replacement) | |
h.each_with_object({}) { |(k,v),g| | |
g[k] = (Hash === v) ? denilize(v) : v == initial ? replacement : v } | |
end | |
h = { "a"=>{ "b"=>{ "c"=>nil } } } | |
denilize(h) #=> { "a"=>{ "b"=>{ "c"=>"" } } } | |
h = { "a"=>{ "b"=>{ "c"=>nil , "d"=>3, "e"=>nil}, "f"=>nil } } | |
denilize(h) #=> { "a"=>{ "b"=>{ "c"=>"" , "d"=>3, "e"=>""}, "f"=>"" } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment