Content deleted Content added
Line 56:
===Ruby===
In [[Ruby (programming language)|Ruby]], symbols can be created with a literal form, or by converting a string<ref name=pickaxe />.
They can be used as an identifier or an interned string<ref name=rubysymbol>{{cite web|last=Kidd|first=Eric|title=13 Ways of Looking at a Ruby Symbol|url=http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol#9|work=Random Hacks|accessdate=10 July 2011}}</ref>. Two symbols with the same contents will always refer to the same object.<ref>http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UI</ref>
It is considered a [[best practice]] to use symbols as keys to an [[associative array]] in Ruby<ref name=rubysymbol /><ref name=wrongreason>{{cite web|title=Using Symbols for the Wrong Reason|url=http://microjet.ath.cx/WebWiki/2005.12.27_UsingSymbolsForTheWrongReason.html|work=Gnomic Notes}}</ref>.
====Examples====
Line 75:
my_symbol.length #=> 11
my_symbol.class #=> Symbol
</source>
Symbols are commonly used to dynamically send messages to (call methods on) objects:
<source lang=ruby>
# same as "aoboc".split("o")
"aoboc".send(:split, "o") #=> ["a", "b", "c"]
</source>
Symbols as keys of an associative array:
Line 81 ⟶ 86:
my_hash[:a] #=> "apple"
my_hash[:b] #=> "banana"
</source>
===Smalltalk===
In [[Smalltalk]], symbols can be created with a literal form, or by converting a string.
They can be used as an identifier or an interned string. Two symbols with the same contents will always refer to the same object.<ref>http://wiki.squeak.org/squeak/uploads/172/standard_v1_9-indexed.pdf ANSI Smalltalk standard.</ref> In most Smalltalk implementations, selectors (method names) are implemented as symbols.
====Examples====
The following is a simple example of a symbol literal in Smalltalk:
<source lang=smalltalk>
my_symbol := #'an identifier' " Symbol literal "
my_symbol := #a " Technically, this is a selector literal. In most implementations, "
" selectors are symbols, so this is also a symbol literal "
</source>
Strings can be coerced into symbols, vice versa:
<source lang=smalltalk>
my_symbol := 'Hello, world!' asSymbol " => #'Hello, world!' "
my_string := #hello: asString " => 'hello:' "
</source>
Symbols conform to the <code>symbol</code> protocol, and their class is called <code>Symbol</code> in most implementations:
<source lang=smalltalk>
my_symbol := #hello_world
my_symbol class " => Symbol "
</source>
Symbols are commonly used to dynamically send messages to (call methods on) objects:
<source lang=smalltalk>
" same as 'foo' at: 2 "
'foo' perform: #at: with: 2 " => $o "
</source>
|