Ruby: symbolize string-values in Hash

Pasha Kalashnikov
1 min readMar 18, 2020

--

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'
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 :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response