
Originally Posted by
ccj64
Hi. Ok, I am new, and I'm sure my question is very basic, but I want to learn RoR and if I don't understand something in detail it bugs the heck out of me. So hopefully someone can help.
I'm going through the Sitepoint book and come to this example:
Code:
class Car
@@number_of_cars = 0
def self.count
@@number_of_cars
end
def initialize
@@number_of_cars += 1
end
end
I created 4 car objects and then did a Car.count and got 4, so it works as advertised, but I have two questions.
1. with the line of code @@number_of_cars = 0, why isn't that variable getting reset to 0 each time I instantiate a new car object? It seems to me it would, but obviously it isn't. Which is a good thing, but I don't udnerstand why it isn't resetting the variable to 0 with each new instance.
When you post code, put code tags around your code to preserve the indenting.
When you create a new instance of a Car, the only thing that executes is this:
Code:
def initialize
@@number_of_cars += 1
end
In that method, @@number_of_cars does not get reset to 0. Ruby parses the class definition once when it first encounters the class definition in your code. That's when 0 gets assigned to @@number_of_cars. Thereafter, when you create an instance of the class, that does not cause ruby to reparse the class definition.
2. I assume it is just 'convention' and the name 'initialize' that makes that method run each time a new instance of the object is created. Correct?
When you create a new object of a class, the initialize() method in the class is called automatically if present.
Bookmarks