How to change hash keys from `Symbol`s to `String`s?
simply call stringify_keys
(or stringify_keys!
)
http://apidock.com/rails/Hash/stringify_keys
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.
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.