Ruby: symbolize string-values in Hash

ActiveSupport gem provided two great methods for Hash:Class:
But how you should symbolize all values in your Hash?
Gem yard provides special class SymbolHash. I was trying to use it in my projects and faced 2 issues:
- It’s not just a Hash. You must update your code because it should be used another way then Hash:Class
- Adding gem
yard
to the dependencies just for one class? It’s not a good idea :)
I didn’t found simple functions to symbolize values in a Ruby Hash. And I just wrote a little function today, which will allow to you to symbolize all string values in your hash:
def deep_symbolize_values(hash)
hash.reduce({}) do |symbol_hash, pair|
symbol_hash.merge! pair[0] => case pair[1].class.to_s
when 'String'
pair[1].to_sym
when 'Hash'
symbolize_values(pair[1])
when 'Array'
pair[1].map(&:to_sym)
else
pair[1]
end
end
end
It works nicely in one of my projects. I would be glad if it will help you :)