views:

53

answers:

3

There are some annoyances with using symbols in hashes. For example, the JSON gem that we use always returns strings from any JSON string that's parsed, so wherever we reference a hash generated from decoding JSON, we have to use a combination of strings and symbols to access hashes.

Style-wise, is it ok to keep things consistent throughout by using strings only?

+3  A: 

Strings are mutable, hence each time you reference "foo" ruby creates a new object. You can test that by calling "foo".object_id in irb. Symbols, on the other hand, are not, so each time you reference :foo ruby returns the same object.

Regarding the "style" and "consistency" you can always use hash.symbolize_keys! for your received json data, this will turn all string keys into symbols. And vice-versa - hash.stringify_keys! to make them strings again.

Eimantas
What if you have a nested hash? I don't think symbolize_keys! or stringify_keys! will update those
apiary
@apiary, write your own, recursive version of `symbolize_keys`, and mix it into `Hash` class.
Pavel Shved
A: 

There is no rule that says a hash key should be a symbol.

The symbol-as-key is seen a lot in Rails as a convention ... Rails makes a lot of use of passing hashes to allow multiple parameters, and the keys in such hashes are often symbols to indicate that they are expected/permissible parameters to a method call.

Toby Hede
A: 

For the indecisive among us:

http://as.rubyonrails.org/classes/HashWithIndifferentAccess.html

fullware