Ruby - Symbol as identifier

Introduction

Being unique, a symbol provides an unambiguous identifier.

You can pass symbols as arguments to methods, like this:

amethod( :deletefiles )

A method might contain code to test the value of the incoming argument:

def amethod( doThis )
    if (doThis == :deletefiles) then
       puts( 'Now deleting files...')
    elsif (doThis == :formatdisk) then
       puts( 'Now formatting disk...')
    else
        puts( "Sorry, command not understood." )
    end
end

Symbols can also be used in case statements where they provide both the readability of strings and the uniqueness of integers:

case doThis
    when :deletefiles then puts( 'deleting')
    when :formatdisk then puts( 'formatting')
    else  puts( "not understood." )
end

The scope in which a symbol is declared does not affect its uniqueness.

Consider the following:

module One
    class MySymbol
    end
    $f1 = :MySymbol
end

module Two
    MySymbol = 1
    $f2 = :MySymbol
end

def MySymbol()
end

$f3 = :MySymbol

Here, the variables $f1, $f2, and $f3 are assigned the symbol :MySymbol in three different scopes: module One, module Two, and the "main" scope.

Variables starting with $ are global, so once created, they can be referenced anywhere.

:MySymbol, and has the same object_id.

# All three display the same id!
puts( $f1.object_id )  #=> 205868
puts( $f2.object_id )  #=> 205868
puts( $f3.object_id )  #=> 205868

Related Topic