开发者

Is it okay to use strings everywhere and never use symbols in Ruby on Rails?

开发者 https://www.devze.com 2023-01-09 07:50 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消