ruby symbols vs string vs constant
on saturday i was asked by a ruby-newbie (sorry - i had to write it :-) ) whats the difference between a symbol, a string and a constant in ruby. even tough there are realy, realy many articles about ruby symbols ( a google search for "ruby symbols" results in 1,340,000 hits - so this is the 1,340,001 aricle covering the topic) there is obviously still some confusion out there. So i try my own definition here.
a symbol is a special class in ruby that is used to define a constant named label. A symbol is not a object reference like a variable or a constant but a label itself. it is often used to define named parameter or keys to maps, because the use of the same symbol results in the same object reference.
a symbol is defined using a :
:my_test_symbol
is a symbol definition. a symbol is not a string. a symbol has a string representation and an object identifier. both are constant. symbols can be compared realy fast because they always result in the same object identifier the comparison only has to use the object identifier. when comparing two strings, == has to do a character wise comparison, because even defining the same string twice results in different objects.
using symbols as hashmap keys looks like this
h = { :name=>"value", :name2=>"value2" }
Ruby on Rails makes heavy use of this
symbols are also used to define attributes of a class using the attr_reader, attr_writer or attr_accessor makro
class Test
attr_accessor :foo
end
this code defines a class in ruby and uses some black metaprogramming magic to define an attribute foo and its accessor function foo and foo=. so writing the following code is equivalent to the one above.
class Test
@foo = nil
def foo
return @foo
end
def foo=(f)
@foo=f
end
end
Symbols are not the same as constants. Contstats are object references like variables that start with a capital letter
PI = 3.14
what's a bit puzzeling in ruby is the fact that constants are not constant at all and can be redefined - altough the interpreter issues a warning (please do not mess with mathematical constants! you never know what the universe will look like after you redefine one!)
See also:
Sonic Pi beatslicing livecoding session
creating midifiles using ruby
Calculating Euclidean Rhythmns using the Bresenham Algorithm
ruby rhyme generator