DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Convert Hash Key Strings To Symbols If They Look Like Them.
Ever read in a YAML file that has symbols in it, but the symbols end up as Strings (eg: ":foo" instead of :foo)? Here's your solution. Hash#key_strings_to_symbols!
class Hash
# Recursively replace key names that should be symbols with symbols.
def key_strings_to_symbols!
r = Hash.new
self.each_pair do |k,v|
if ((k.kind_of? String) and k =~ /^:/)
v.key_strings_to_symbols! if v.kind_of? Hash and v.respond_to? :key_strings_to_symbols!
r[k.slice(1..-1).to_sym] = v
else
v.key_strings_to_symbols! if v.kind_of? Hash and v.respond_to? :key_strings_to_symbols!
r[k] = v
end
end
self.replace(r)
end
end




