I was playing around with class variables, and I knew that I could override a class variable in a subclass but I didn't realize where I call a class method matters. For example;
class Vehicle
@@wheels = 4
def self.wheels
@@wheels
end
end
puts Vehicle.wheels #4
puts Vehicle.wheels #4
puts Vehicle.wheels #4
class Motorcycle < Vehicle
@@wheels = 2
end
The puts
statement outputs 4, that all makes sense to me because I figured that you @@wheels
is not overridden until an object is instantiated from the Motorcycle
class. So then I did this:
class Vehicle
@@wheels = 4
def self.wheels
@@wheels
end
end
class Motorcycle < Vehicle
@@wheels = 2
end
puts Vehicle.wheels #2
puts Vehicle.wheels #2
puts Vehicle.wheels #2
Now once I move those three lines to after the class Motorcycle
they output 2... even though a Motorcycle
object hasn't been instantiated. This confuses me. In detail what is happening here? Is it because class variables are loaded when we try to access it? How is this possible?