David Alan Black <dblack / candle.superlink.net> writes:

> Hello --
> 
> I've been puzzling over Ruby's treatment of class variables -- not so
> much the "what" as the "why".
> 
> It seems strange to me that a class somewhere off in one side of an
> inheritance tree can affect a class variable all over the tree.
> 
> For illustration purposes (no claims of greatness of design):
> 
>    class Vehicle
>      @@tires = 0
>      def tire_count
>        @@tires
>      end
>    end
> 
>    class Car < Vehicle
>      @@tires = 4
>    end
> 
>    class Bike < Vehicle
>      @@tires = 2
>    end
> 
>    puts Car.new.tire_count  # => 2
> 
> 
> Class variables seem to be not so much per class as per class
> hierarchy or family.  I can't quite figure out why they work this way,
> rather than working like instance methods (so that redefinition in a
> child class stops the search process up the inheritance path).

Let me try. The key is that classes are objects too, and they have their
own inheritance tree, complete with methods and instance variables
(attributes).

	Vehicle ----------- Vehicle class (with attr @@tires)
	  |  \			|      \
	Car  Bike --------  Car class  Bike class

In this case, the object that represents the Vehicle class has an instance
variable called 'tires'. That instance variable exists in the Vehicle class
object.

The line "@@tires = 0" creates a new instance variable inside the Vehicle
class object. The lines "@@tires = 4" and "@@tiers = 2" assign new values
to that instance variable, they don't declare new instances.

Jim
-- 
Jim Menard, jimm / io.com, http://www.io.com/~jimm/
"Don't eat crackers in the bed of your future or you'll get ... scratchy!"
    -- The Tick