Class Variables

suggest change

Class variables have class-wide scope and can be declared anywhere in the class. A variable is a class variable when its name starts with @@.

class Dinosaur
    @@classification = "Like a Reptile, but like a bird"
    
    def self.classification
        @@classification
    end

    def classification
        @@classification
    end
end

dino = Dinosaur.new
dino.classification
# => "Like a Reptile, but like a bird"
  
Dinosaur.classification
# => "Like a Reptile, but like a bird"

Class variables are shared between a class and its subclasses, and a child class can overwrite them:

class TRex < Dinosaur
    @@classification = "Big teeth bird!"
end

TRex.classification
# => "Big teeth bird!"

Dinosaur.classification
# => "Big teeth bird!"

This behaviour is unwanted most of the time and can be circumvented by using class-level instance variables.

Class variables defined in a module do not overwrite the including class’s class variables. This snippet continues from the previous one, where TRex set @@classification:

module SomethingStrange
    @@classification = "Something Strange"
end

class DuckDinosaur < Dinosaur
    include SomethingStrange
end

DuckDinosaur.class_variables
# => [:@@classification]
SomethingStrange.class_variables
# => [:@@classification]

DuckDinosaur.classification
# => "Big teeth bird!"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents