Sebastian Hungerecker
6/30/2008 8:42:00 AM
Sean Murphy wrote:
> Instant Variables I am completely mystified on their purpose and their
> difference between a local variable.
They're called instance variables, not instant variables. And they're called
that because they're specific to an instance of a class (i.e. to an object).
For example take the following class:
class Foo
def initialize(bar)
@bar = bar
end
def bar
@bar
end
end
f1 = Foo.new(5)
f2 = Foo.new(4)
f1.bar #=> 5
f2.bar #=> 4
So here you have two instances of the class Foo. One instance has the value 5
stored in the instance variable @bar, the other one the value 4. As long as
f1 and f2 exist you will be able to access their values for @bar via the bar-
method. If @bar were a local variable, it would disappear after the initialize
method is done and thus would not be accessible from the bar method. If @bar
was a global variable, it would not be object-specific, so f1.bar and f2.bar
would return the same thing.
HTH,
Sebastian
--
Jabber: sepp2k@jabber.org
ICQ: 205544826