How do I convert a Ruby hash so that all of its keys are symbols?

RubyHash

Ruby Problem Overview


I have a Ruby hash which looks like:

{ "id" => "123", "name" => "test" }

I would like to convert it to:

{ :id => "123", :name => "test" }

Ruby Solutions


Solution 1 - Ruby

hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}

@mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent to_sym, just want to remind that in Ruby 1.8 1.to_sym == nil, so playing with some key types can be misleading):

hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}

s2s = 
  lambda do |h| 
    Hash === h ? 
      Hash[
        h.map do |k, v| 
          [k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]] 
        end 
      ] : h 
  end

s2s[hash] #=> {:d=>"e", #<Object:0x100396ee8>=>"g", :a=>{:b=>"c"}}

Solution 2 - Ruby

If you happen to be in Rails then you'll have symbolize_keys:

> Return a new hash with all keys converted to symbols, as long as they respond to to_sym.

and symbolize_keys! which does the same but operates in-place. So, if you're in Rails, you could:

hash.symbolize_keys!

If you want to recursively symbolize inner hashes then I think you'd have to do it yourself but with something like this:

def symbolize_keys_deep!(h)
  h.keys.each do |k|
    ks    = k.to_sym
    h[ks] = h.delete k
    symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
  end
end

You might want to play with the kind_of? Hash to match your specific circumstances; using respond_to? :keys might make more sense. And if you want to allow for keys that don't understand to_sym, then:

def symbolize_keys_deep!(h)
  h.keys.each do |k|
    ks    = k.respond_to?(:to_sym) ? k.to_sym : k
    h[ks] = h.delete k # Preserve order even when k == ks
    symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
  end
end

Note that h[ks] = h.delete k doesn't change the content of the Hash when k == ks but it will preserve the order when you're using Ruby 1.9+. You could also use the [(key.to_sym rescue key) || key] approach that Rails uses in their symbolize_keys! but I think that's an abuse of the exception handling system.

The second symbolize_keys_deep! turns this:

{ 'a' => 'b', 'c' => { 'd' => { 'e' => 'f' }, 'g' => 'h' }, ['i'] => 'j' }

into this:

{ :a => 'b', :c => { :d => { :e => 'f' }, :g => 'h' }, ['i'] => 'j' }

You could monkey patch either version of symbolize_keys_deep! into Hash if you really wanted to but I generally stay away from monkey patching unless I have very good reasons to do it.

Solution 3 - Ruby

If you are using Rails >= 4 you can use:

hash.deep_symbolize_keys
hash.deep_symbolize_keys!

or

hash.deep_stringify_keys
hash.deep_stringify_keys!

see http://apidock.com/rails/v4.2.1/Hash/deep_symbolize_keys

Solution 4 - Ruby

Just in case you are parsing JSON, from the JSON docs you can add the option to symbolize the keys upon parsing:

hash = JSON.parse(json_data, symbolize_names: true)

Solution 5 - Ruby

Victor Moroz provided a lovely answer for the simple recursive case, but it won't process hashes that are nested within nested arrays:

hash = { "a" => [{ "b" => "c" }] }
s2s[hash] #=> {:a=>[{"b"=>"c"}]}

If you need to support hashes within arrays within hashes, you'll want something more like this:

def recursive_symbolize_keys(h)
  case h
  when Hash
    Hash[
      h.map do |k, v|
        [ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ]
      end
    ]
  when Enumerable
    h.map { |v| recursive_symbolize_keys(v) }
  else
    h
  end
end

Solution 6 - Ruby

Try this:

hash = {"apple" => "banana", "coconut" => "domino"}
 # => {"apple"=>"banana", "coconut"=>"domino"} 

hash.tap do |h|
  h.keys.each { |k| h[k.to_sym] = h.delete(k) }
end
 # => {:apple=>"banana", :coconut=>"domino"} 

This iterates over the keys, and for each one, it deletes the stringified key and assigns its value to the symbolized key.

Solution 7 - Ruby

If you're using Rails (or just Active Support):

{ "id" => "123", "name" => "test" }.symbolize_keys

Solution 8 - Ruby

Here's a Ruby one-liner that is faster than the chosen answer:

hash = {"apple" => "banana", "coconut" => "domino"}
#=> {"apple"=>"banana", "coconut"=>"domino"}

hash.inject({}){|h,(k,v)| h[k.intern] = v; h}
#=> {:apple=>"banana", :coconut=>"domino"}

Benchmark results:

n = 100000

Benchmark.bm do |bm|
  bm.report { n.times { hash.inject({}){|h,(k,v)| h[k.intern] = v; h} } }
  bm.report { n.times { Hash[hash.map{ |k, v| [k.to_sym, v] }] } }
end

# =>       user     system      total        real
# =>   0.100000   0.000000   0.100000 (  0.107940)
# =>   0.120000   0.010000   0.130000 (  0.137966)

Solution 9 - Ruby

Starting with Ruby 2.5 you can use the transform_key method.

So in your case it would be:

h = { "id" => "123", "name" => "test" }
h.transform_keys!(&:to_sym)      #=> {:id=>"123", :name=>"test"}

Note: the same methods are also available on Ruby on Rails.

Solution 10 - Ruby

I'm partial to:

irb
ruby-1.9.2-p290 :001 > hash = {"apple" => "banana", "coconut" => "domino"}
{
      "apple" => "banana",
    "coconut" => "domino"
}
ruby-1.9.2-p290 :002 > hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
{
      :apple => "banana",
    :coconut => "domino"
}

This works because we're iterating over the hash and building a new one on the fly. It isn't recursive, but you could figure that out from looking at some of the other answers.

hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }

Solution 11 - Ruby

You can also extend core Hash ruby class placing a /lib/hash.rb file :

class Hash
  def symbolize_keys_deep!
    new_hash = {}
    keys.each do |k|
      ks    = k.respond_to?(:to_sym) ? k.to_sym : k
      if values_at(k).first.kind_of? Hash or values_at(k).first.kind_of? Array
        new_hash[ks] = values_at(k).first.send(:symbolize_keys_deep!)
      else
        new_hash[ks] = values_at(k).first
      end
    end

    new_hash
  end
end

If you want to make sure keys of any hash wrapped into arrays inside your parent hash are symbolized, you need to extend also array class creating a "array.rb" file with that code :

class Array
  def symbolize_keys_deep!
    new_ar = []
    self.each do |value|
      new_value = value
      if value.is_a? Hash or value.is_a? Array
        new_value = value.symbolize_keys_deep!
      end
      new_ar << new_value
    end
    new_ar
  end
end

This allows to call "symbolize_keys_deep!" on any hash variable like this :

myhash.symbolize_keys_deep!

Solution 12 - Ruby

def symbolize_keys(hash)
   new={}
   hash.map do |key,value|
        if value.is_a?(Hash)
          value = symbolize_keys(value) 
        end
        new[key.to_sym]=value
   end        
   return new

end  
puts symbolize_keys("c"=>{"a"=>2,"k"=>{"e"=>9}})
#{:c=>{:a=>2, :k=>{:e=>9}}}


      
               


      

Solution 13 - Ruby

Here's my two cents,

my version of symbolize_keys_deep! uses the original symbolize_keys! provided by rails and just makes a simple recursive call to Symbolize sub hashes.

  def symbolize_keys_deep!(h)
    h.symbolize_keys!
    h.each do |k, v|
      symbolize_keys_deep!(v) if v.is_a? Hash
    end
  end

Solution 14 - Ruby

Facets' Hash#rekey is also a worth mentioning.

Sample:

require 'facets/hash/rekey'
{ "id" => "123", "name" => "test" }.deep_rekey
=> {:id=>"123", :name=>"test"}

There is also a recursive version:

require 'facets/hash/deep_rekey'
{ "id" => "123", "name" => {"first" => "John", "last" => "Doe" } }.deep_rekey
=> {:id=>"123", :name=>{:first=>"John", :last=>"Doe"}}

Solution 15 - Ruby

Here's a little recursive function to do a deep symbolization of the keys:

def symbolize_keys(hash)
  Hash[hash.map{|k,v| v.is_a?(Hash) ? [k.to_sym, symbolize_keys(v)] : [k.to_sym, v] }]
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioned1tView Question on Stackoverflow
Solution 1 - RubyVictor MorozView Answer on Stackoverflow
Solution 2 - Rubymu is too shortView Answer on Stackoverflow
Solution 3 - RubyMRifatView Answer on Stackoverflow
Solution 4 - RubyAlexander PopovView Answer on Stackoverflow
Solution 5 - RubypjeView Answer on Stackoverflow
Solution 6 - RubyJohn FeminellaView Answer on Stackoverflow
Solution 7 - RubybonkydogView Answer on Stackoverflow
Solution 8 - RubyChakaitosView Answer on Stackoverflow
Solution 9 - RubyPaulo FidalgoView Answer on Stackoverflow
Solution 10 - Rubythe Tin ManView Answer on Stackoverflow
Solution 11 - RubyDavid FabreguetteView Answer on Stackoverflow
Solution 12 - Rubykajal agarwalView Answer on Stackoverflow
Solution 13 - RubyDon GiulioView Answer on Stackoverflow
Solution 14 - RubySergikonView Answer on Stackoverflow
Solution 15 - Rubyuser3250006View Answer on Stackoverflow