Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}}
like image 344
dhrubo_moy Avatar asked Dec 03 '22 14:12

dhrubo_moy


2 Answers

If you are using ActiveSupport already or are open to using it, then deep_stringify_keys is what you're looking for.

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_stringify_keys
# => {"person"=>{"name"=>"Rob", "age"=>"28"}}
like image 73
Michael Kohl Avatar answered Dec 21 '22 22:12

Michael Kohl


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
like image 37
Jake H Avatar answered Dec 21 '22 23:12

Jake H