Download this source
# advanced invocation, symbols, etc. Lets have a var
myvar = "This is my var"
# we can make a symbol, which literally corresponds to the symbol in the code.
mysym = :myvar
# The symbol is a thing in itself. We can use it directly
puts mysym, "Name is #{mysym.id2name}"
# and, by using 'eval' with the name, we can dereference it to get at
# of any current variable (or method - see below) that has that name and
# is in scope
puts "Value is #{eval(mysym.id2name)}"
# Obviously a symbol could also refer to a method. The 'Method' module provides
# us with a way to grab a method from a class given a symbol.
class MyClass
def my_method(a)
puts a
end
end
# The key point to note is that the symbol _isn't_ either a variable, or a
# method, or anything - they may not even be a variable or method corresponding
# to it. There's no magic really - it's just an immutable string from our
# point of view.
mc = MyClass.new
meth = mc.method(:my_method)
meth.call("A Value")
# This has some fairly useful ramifications, but take care - it's easy to
# get in a mess with what comes from where ;)
def call_it(m, a)
m.call(a)
end
call_it(meth,"Another value")
Running this outputs:
myvar
Name is myvar
Value is This is my var
A Value
Another value

