關於RUBY :Symbol的定義
對於初學RUBY的人,不管是新手或有程式底子,也許多少都會對Symbol的功用感到疑惑吧,而我也是那麼一個.
翻了很多文章,在網路上的高手解釋之後,我多少大概瞭解SYMBOL的功用.
打開command line輸入ri Symbol看看它的解釋.
| Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts. |
這段解釋定義了Symbol為一個呈現"name"與"string"的object.
再看看ri所提供的Symbol範例 :
module One class Fred end $f1=:Fred end module Two Fred=1 $f2=:Fred end def Fred() end $f3=:Fred $f1.id #=>2514190 $f2.id #=>2514190 $f3.id #=>2514190
以上面這段程式看起來,不管f1,f2,f3都指向同一個物件.
這解釋了第一個特性,每個SYMBOL都只具一個實體,"唯一性"
再來,打開irb輸入下面代碼,讓我們看看它與字串的關係.
a= :str b= "str" a[0] #=> undefined method [] for :str:Symbol b[0] #=> 115 a.to_s[0] #=> 115 a.size #=> undefined method size for :str:Symbol
由上面的範例,我們可以知道Symbol跟String是不一樣的.
儘管我們可以將它to_s轉為String後再進行修改,但我們無法對Symbol直接修改.
(不過.... 在Ruby 1.9已經將Symbol加入了各種String的功能,如size,length甚至是Regexp, =~ ,所以Symbol和String是越來越像了.)
那麼,Symbol到底是幹麻的?
其實大多數人拿它來當Hash的key,或是name, identifier.
也許因為效能比較好,它是唯一性的. 再加上你不管到哪都是指向同一個物件,有點類似c指標.
而且1.9以後可以直接對Symbol作操作,更提高了Symbol的功能.
Symbol的用法,如同之前所說,如果你還有其他用法或見解,請一定要告訴我,大家一起進步.
--延伸閱讀
Digging into Ruby Symbols
Yet Another Blog about Ruby Symbols
Symbols, Strings, Methods, and Variables
Symbols Are Not Immutable Strings

