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?
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" ).
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.
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.
simply call stringify_keys
(or stringify_keys!
)
http://apidock.com/rails/Hash/stringify_keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With