Re: question about class variables and instance variables



On Jan 31, 2006, at 11:29 AM, Eric D. wrote:

I've some difficolties with instance variables and classe variables

With :

   class A
       def foo
          @foo
       end
       def bar
          @@bar
       end
    end

    a = A.new

---------                  ------------                  ------------
|       |                  |          |                  |          |
|  a    |--(instance_of)->-|    A     |--(instance_of)->-|  Class   |
|       |                  |          |                  |          |
---------                  ------------                  ------------

a is an instance of A which itself is an instance of Class
@foo is an instance variable, so it is stored in box "a"
@@bar is a class variable, so it is stored in box "A"


if I do something like the following :

   class A
      def A.strange
         @strange
      end
   end

Where is stored my @strange ? I had the hypothesis that @strange in the
"A" context was equivalent to @@strange in the "a" context but the
following code prove me to be wrong :


  class A
      def A.strange
         @strange
      end
      def strange=( val )
         @@strange = val
      end
  end

  a = A.new
  a.strange= 2
  p A.strange # output is nil, not 2


Could someone explain me where to place this @strange ? in which box could I store it ?

instance variables are always stored in the instance self.

class variables are shared between a class, its instances, its subclasses and its subclass instances.

Consider:

class A
  @@a_1 = :one
  def initialize
    @@a_2 = :two
  end
end

A.new

class B < A
  p @@a_1, @@a_2

  @@b_1 = :three
  def initialize
    @@b_2 = :four
  end

  def print
  p @@a_1, @@a_2, @@b_1, @@b_2
  end
end

class A
  x = @@b_1 rescue 'not found'
  y = @@b_2 rescue 'not found'

  p x, y
end

B.new.print

--
Eric Hodel - drbrain@xxxxxxxxxxxx - http://segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com




.



Relevant Pages

  • [ANN] main-3.0.1
    ... def runputs 'installing...' ... def runputs 'uninstalling...' ... and auto-generation of usage messages can really streamline ... int(foo): the cast is int, ...
    (comp.lang.ruby)
  • virtual metaclasses explanation
    ... def ClassA ... class ClassB < ClassC ... stuart = ClassB.methodY ... def m1"foo" end ...
    (comp.lang.ruby)
  • Re: question about class variables and instance variables
    ... def foo ...
    (comp.lang.ruby)
  • [ANN] main-2.8.3
    ... a class factory and dsl for generating command line programs real ... def runputs 'installing...' ... and auto-generation of usage messages can really ... int(foo): the cast is int, ...
    (comp.lang.ruby)
  • Re: Getting rid of "self."
    ... def __init__: ... > basis of information available at the time the decorator executes. ... I am content with declaring them like the selfless ... foo = _foo ...
    (comp.lang.python)