Skip to content

Instantly share code, notes, and snippets.

@StanBoyet
Last active September 28, 2018 08:28
Show Gist options
  • Save StanBoyet/a76fb58affff4ceca5120dc495714824 to your computer and use it in GitHub Desktop.
Save StanBoyet/a76fb58affff4ceca5120dc495714824 to your computer and use it in GitHub Desktop.
Recursively replace a value `initial` by `replacement`
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