Ruby: symbolize string-values in Hash

author @no___tea/

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:

  1. It’s not just a Hash. You must update your code because it should be used another way then Hash:Class
  2. 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'
when 'Hash'
when 'Array'

It works nicely in one of my projects. I would be glad if it will help you :)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store