Ruby Hash: Convert String keys to Symbols
posted: 19.08.2009Ever had a hash which contained strings as keys and needed symbols instead? I do: From a REXML::Document I created a hash. Unfortunately, the keys were all strings and I needed them to be symbols at some other point in the app. Thank god, Ruby is capable of extending any object “on the fly”. So, I wrote a simple extension to Hash, which you might find useful as well:
class Hash
#take keys of hash and transform those to a symbols
def self.transform_keys_to_symbols(value)
return value if not value.is_a?(Hash)
hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
return hash
end
end
Usage is:
a = { "key" => 123, "inner_hash" => { "another_key" => "blabla" }}
Hash.transform_keys_to_symbols(a)
#returns
a = { :key => 123, :inner_hash => { :another_key => "blabla" }}



December 17th, 2009 at 10:12
Thank you!
Exactly what I was looking for!
May 14th, 2010 at 19:21
You have a spelling error at Hash.transform_keys_to_symbol(v);
May 15th, 2010 at 11:45
Thanks, Rick. I corrected it.
December 18th, 2011 at 14:21
I know this was a long time ago, but refactored:
class Hash
#take keys of hash and transform those to a symbols
def self.transform_keys_to_symbols(value)
return value unless value.is_a?(Hash)
value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
end
end