How to replace all nil value with "" in a ruby hash recursively?
hash, proc, ruby
Solution
Here is a recursive method that does not change the original hash.
Code
def denilize(h)
h.each_with_object({}) { |(k,v),g|
g[k] = (Hash === v) ? denilize(v) : v.nil? ? '' : v }
end
Examples
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"=>"" } }
Problem
``` str = "<a><b><c></c></b></a>" hash = Hash.from_xml(str) # => {"a"=>{"b"=>{"c"=>nil}}} ``` How can I replace all `nil`s in a Hash to `""` so that the hash becomes: ``` {"a"=>{"b"=>{"c"=>""}}} ```