>>>>> "G" == Gavin Sinclair <gsinclair / soyabean.com.au> writes:

G> (Actually, David, if you want to blabber on about class local variables, I'm
G> all ears ;)


 Well, I'll try to explain where is the problem with instance
 variables. Imagine that you have

   class A
      def initialize
         @a = 12
      end

      def show
         puts @a
      end
   end

   class B < A
      def show
         puts @a
         super
      end
   end

   b = B.new
   b.show

 What you must see in my example is that the instance variable is
 associated with self (i.e. the object) and ruby will access the same
 variable in A#show and B#show. This is just what you want and it work
 fine, but now imagine that the class A was written by someone and the
 class B by written by another person, and these 2 persons write

   class A
      def initialize
         @a = 12
      end

      def show
         puts @a
      end
   end

   class B < A
      def initialize
         @a = 24
      end

      def display
         puts @a
      end
   end

   b = B.new
   b.display
   b.show

 The person which has written B has defined an instance variable `@a'
 without knowing that this instance variable was also defined by the
 person which has written A, and ruby just display the same value.

 It exist some case where you want that an instance variable can be
 accessed and modified only within a class. This mean that the instance
 variable which is associated with an object will be "class local"

 In this case, the proposition was to write


   class A
      def initialize(value)
         @_a = value
      end

      def show
         puts @_a
      end
   end

   class B < A
      def initialize(value)
         @_a = value
         super(2 * value)
      end

      def display
         puts @_a
      end
   end

   b = B.new(12)
   b.display   # ===> 12
   b.show      # ===> 24

 i.e. you have different value of @_a which will depend on the class.

 You have "class local variable" :-)


Guy Decoux