Can't get the hang of symbols in Ruby

独自空忆成欢 提交于 2019-12-05 10:50:09

symbols in ruby are a way to efficiently utilize immutable strings. For example, suppose you want to use the string "my_key" as a hash key. Simply using the string is a waste of both space and efficiency since each time you specify the hash key "my_key" you are creating a different string instance in a different memory location even though the string value contents are the same! So if you have 100 instances of my_hash['my_key'] you have 100 instance of the string 'my_key'. Not so with the symbol :my_key. There is only ever one instance of :my_key no matter how many times you utilize it!

You should use symbols where you would normally uses an immutable string as an identifier.

The way to understand this is to consider that String is a Ruby object and it is not specified to be immutable. As a result, a number of optimizations are unavailable to the language processor and a reader of the code may or may not understand whether a given string is functioning as a mutable data structure or as the key to something.

But symbols are immutable, so they have unique instances. They are also easy to type, and the use of a symbol clearly indicates "identifier" or "token" to anyone reading the code later.

Finally, class Symbol implements the explicit conversion #to_s, so symbols are safe to use in expressions where you know #to_s will be called, such as in ERB templates or in I/O operations.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!