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 o开发者_开发百科nly?
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.
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.
For the indecisive among us:
http://as.rubyonrails.org/classes/HashWithIndifferentAccess.html
精彩评论