I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbol
s to String
s. 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?
simply call
stringify_keys
(orstringify_keys!
)http://apidock.com/rails/Hash/stringify_keys
stringify_keys from rails
http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys
new_hash will be same as your_hash but with string keys
I came here to see if there was something better than:
But I think I'll stick with what I have.
Use
stringify_keys
/stringify_keys!
methods of theHash
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.there is a nice library that does the trick, the library is "facets/hash/rekey" and the method is rekey!. Se my example below of how to use it. It is just a copy past of