大家如何理解ruby中的符号变量
如题?请各抒己见,交流一下。
[解决办法]
symbol is symbol, like a tag, this tag is a element, this element memory address is constant
symbol is like string, but there is some different.
like below:
:example
:example
"example"
"example"
they can convert each other, but if you check the object_id, you will find,
:example #=>xxx
:example #=>xxx
"example" #=>xxxxxy
"example" #=>xxxxxz
string object_id of two "example" is different
symbol object_id of two :example is same
some scenario like
you generate a hash like example_hash = {"ruby"=>"rails",....}
if you have many example_hash, you will find, Oops! you out memory.
so you need to use :ruby to instead of "ruby"
[解决办法]
这里有详细解释 http://www.ruby-doc.org/core/Symbol.html
[解决办法]
[17] pry(main)> :key.object_id
=> 100808
[18] pry(main)> :key.object_id
=> 100808
[19] pry(main)> 'key'.object_id
=> 34255720
[20] pry(main)> 'key'.object_id
=> 43597460