ruby symbols vs string vs constant

Nikolaus Gradwohl2009-02-10T03:13:00+01:00

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!)

Tweet This! submit to reddit Digg!   Tags: | no comments | no trackbacks

See also:

ruby rhyme generator
Curling Animation II
Blinking Logfile Map
Curling Recursion
Set operations on ruby arrays

Trackbacks

Comments

Leave a response

Leave a comment