dhrubo_moy dhrubo_moy - 3 months ago 10
Ruby Question

How to recursively convert keys of Ruby Hashes that are symbols to String

Suppose I have following hash or nested hash:

h = { :a1 => { :b1 => "c1" },
:a2 => { :b2 => "c2"},
:a3 => { :b3 => "c3"} }


I want to create a method that takes hash as a parameter and recursively convert all the keys (keys that are symbol eg.
:a1
) to String (eg.
"a1"
). So far I have come up with the following method which doesn't work and returns
{"a1"=>{:b1=>"c1"}, "a2"=>{:b2=>"c2"}, "a3"=>{:b3=>"c3"}}
.:

def stringify_all_keys(hash)
stringified_hash = {}
hash.each do |k, v|
stringified_hash[k.to_s] = v
if v.class == Hash
stringify_all_keys(stringified_hash[k.to_s])
end
end
stringified_hash
end


What am I doing wrong and how do a get all the keys converted to string like this:

{"a1"=>{"b1"=>"c1"}, "a2"=>{"b2"=>"c2"}, "a3"=>{"b3"=>"c3"}}

Answer

Didn't test this, but looks about right:

def stringify_all_keys(hash)
  stringified_hash = {}
  hash.each do |k, v|
    stringified_hash[k.to_s] = v.is_a?(Hash) ? stringify_all_keys(v) : v
  end
  stringified_hash
end