Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all nil value with "" in a ruby hash recursively?

Tags:

ruby

hash

proc

str = "<a><b><c></c></b></a>"
hash = Hash.from_xml(str)
# => {"a"=>{"b"=>{"c"=>nil}}}

How can I replace all nils in a Hash to "" so that the hash becomes:

{"a"=>{"b"=>{"c"=>""}}}
like image 699
ohho Avatar asked May 28 '14 04:05

ohho


1 Answers

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"=>"" } } 
like image 77
Cary Swoveland Avatar answered Sep 19 '22 14:09

Cary Swoveland