Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 697
user12882 Avatar asked May 11 '12 10:05

user12882


People also ask

What is HashWithIndifferentAccess?

HashWithIndifferentAccess is the Rails magic that paved the way for symbols in hashes. Unlike Hash , this class allows you to access data using either symbols ( :key ) or strings ( "key" ).

How do you merge hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

What are symbols in Ruby?

Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.


1 Answers

simply call stringify_keys (or stringify_keys!)

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

like image 70
Viktor Trón Avatar answered Sep 28 '22 00:09

Viktor Trón