Symbol (programming): Difference between revisions

Content deleted Content added
Javascript -> JavaScript
m Support: lang=irb
Line 7:
{| class="wikitable sortable"
|-
|! language || type name(s) || example literal(s)
|-
| [[ANSI]] [[Common Lisp]] || symbol, keyword || <tt>symbol</tt>, <tt>:keyword</tt>
Line 107:
</source>
Strings can be coerced into symbols, vice versa:
<source lang=rubyirb>
irb(main):001:0> my_symbol = "Hello, world!".intern #
=> :"Hello, world!"
irb(main):002:0> my_symbol = "Hello, world!".to_sym #
=> :"Hello, world!"
irb(main):003:0> my_string = :hello.to_s
=> "hello"
</source>
Symbols are objects of the <code>Symbol</code> class in Ruby:<ref name="rdocsymbol">{{cite web|title=Symbol|url=http://www.ruby-doc.org/core/classes/Symbol.html|work=Ruby Documentation|accessdate=10 July 2011}}</ref>
<source lang=rubyirb>
irb(main):004:0> my_symbol = :hello_world
=> :hello_world
my_symbol.length #=> 11
irb(main):005:0> my_symbol.class #=>length Symbol
=> 11
irb(main):006:0> my_symbol.class
=> Symbol
</source>
Symbols are commonly used to dynamically send messages to (call methods on) objects:
<source lang=rubyirb>
# same asirb(main):007:0> "aoboc".split("o")
"aoboc".send(:split, "o") #=> ["a", "b", "c"]
irb(main):008:0> "aoboc".send(:split, "o") # same result
=> ["a", "b", "c"]
</source>
Symbols as keys of an associative array:
<source lang=rubyirb>
irb(main):009:0> my_hash = { a: "apple", b: "banana" }
my_hash[=> {:a] #=> "apple", :b=>"banana"}
irb(main):010:0> my_hash[:ba] #=> "banana"
=> "apple"
irb(main):011:0> my_hash[:b]
=> "banana"
</source>