liveBook · Manning

Class-hierarchy scope

As explained in The Well-Grounded Rubyist, Fourth Edition

Class-hierarchy scope is the Ruby visibility rule under which a class variable is shared by a class and its descendants and their instances.

Suppose `Parent` sets `@@value = 100` and its subclass `Child` sets `@@value = 200`. Reading `@@value` in `Parent` now prints `200`. The assignment in `Child` changed a shared variable; it did not create a separate one. section 5.2.5

class Parent
  @@value = 100         #1
end
class Child < Parent
  @@value = 200       #2
end
class Parent
  puts @@value         #3
end

Run this small hierarchy example to see a subclass assignment change the value read in its parent. section 5.2.5

That reach can be useful for state accessed by both class methods and instances. A car counter, for example, can be updated during instance initialization and read through a class method. But descendants share the counter too: `Hybrid < Car` does not get an independent `@@total_count`. As subclasses and their instances accumulate, this state can become difficult to manage. section 5.2.5

If each class needs its own count, use an instance variable on the class object instead. A `total_count` method can read `@total_count`, while initialization updates `self.class.total_count`; a subclass then maintains its own total. section 5.2.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through parent–child assignments and a counter design, then contrasts a class-object instance variable.
Examples
Uses a parent–child value change and car counts shared with a subclass.
What it assumes
Assumes familiarity with Ruby classes, subclasses, and instance variables.
What you can do after
Evaluate/understand when a class variable will share state across descendants and when a class-object instance variable better separates it.
How it connects
Connects class variables to inheritance, instance variables, class methods, and `self.class`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.