An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby's instance variables are never public ) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the
nilvalue until they are initialized.
Instance variables of ruby do not need declaration. This implies a flexible structure of objects. In fact, each instance variable is dynamically appended to an object when it is first referenced.
ruby> class InstTest | def set_foo(n) | @foo = n | end | def set_bar(n) | @bar = n | end | end nil ruby> i = InstTest.new #<InstTest:0x83678> ruby> i.set_foo(2) 2 ruby> i #<InstTest:0x83678 @foo=2> ruby> i.set_bar(4) 4 ruby> i #<InstTest:0x83678 @foo=2, @bar=4>
Notice above that i does not report a value for @bar until after the set_bar method is invoked.