Symbols
Symbols look like variables, however, with a colon (:
) prefixed. For example, :symbol_1
. Symbols need not be predeclared and assigned a value. Ruby guarantees that the symbol has a particular value, no matter where it appears in a Ruby program.
Symbols are very useful because a given symbol name refers to the same object throughout a Ruby program. Two strings with the same content are two different objects; however, for a given name, there can only be one single symbol object. Let's examine the following example to illustrate this fact:
irb 2.1-head :001 > puts "string".object_id 70168328185680 => nil 2.1-head :002 > puts "string".object_id 70168328173400 => nil 2.1-head :003 > puts :symbol.object_id 394888 => nil 2.1-head :004 > puts :symbol.object_id 394888 nil
As you can see, we started by creating a string object with the string
value and sought its object ID using the object_id
method. Next, we tried the same thing once more. In both the cases, we received...