How to change hash keys from `Symbol`s to `String`s?

54,993

Solution 1

simply call stringify_keys (or stringify_keys!)

http://apidock.com/rails/Hash/stringify_keys

Solution 2

Use stringify_keys/stringify_keys! methods of the Hash class.

You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.

Solution 3

stringify_keys is nice, but only available in Rails. Here's how I would do it in a single line, with zero dependencies:

new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]

This works on Ruby 1.8.7 and up. If you are working with Ruby 2.1, you can do:

new_hash = a.collect{|k,v| [k.to_s, v]}.to_h

Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.

Solution 4

hash = hash.transform_keys(&:to_s) turns all keys from symbols into strings.

More here: https://ruby-doc.org/core-2.6.3/Hash.html#method-i-transform_keys

This was added in ruby 2.5: https://bugs.ruby-lang.org/issues/13583

Solution 5

stringify_keys from rails

http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys

hash = { name: 'Rob', age: '28' }
hash.stringify_keys
# => { "name" => "Rob", "age" => "28" }
Share:
54,993
user12882
Author by

user12882

Updated on July 05, 2022

Comments

  • user12882
    user12882 almost 2 years

    I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.

    How can I make that by using less code as possible?

  • Romain Paulus
    Romain Paulus over 10 years
    deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys
  • Tom
    Tom over 5 years
    Be careful with this strategy as it will also turn any values that are symbols into strings.
  • Arian Faurtosh
    Arian Faurtosh over 3 years
    This won't do deep transform'ing