Symbols and Variables

To understand the relationship between a symbol and an identifier such as a variable name, take a look at the symbols_2.rb program. It begins by assigning the value 1 to a local variable, x. It then assigns the symbol :x to a local variable, xsymbol:

symbols_2.rb

x = 1
xsymbol = :x

At this point, there is no obvious connection between the variable x and the symbol :x. I have declared a method that simply takes some incoming argument and inspects and displays it using the p method. I can call this method with the variable and the symbol:

def amethod( somearg )
    p( somearg )
end

# Test 1
amethod( x )
amethod( :x )

This is the data that the method prints as a result:

1
:x

In other words, the value of the x variable is 1, since that’s ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.