Kaye Ng wrote in post #985934:
@@number_of_squares = @@number_of_squares + 1
@@number_of_squares = 1
a = Square.new #would return 1
b = Square.new #would return 2
puts Square.count #2 would be printed on the screen
My question is: why is the “self” necessary in “def self.count”.
I don’t understand the logic behind it.
It isn’t necessary:
@@number_of_squares ||= 0
@@number_of_squares += 1
a = Square.new
b = Square.new
puts a.count #2
…but the way in which you define the method determines how you can
call the method. You can choose to define a “class method” or an
“instance method”. A class method is called using the class, and an
instance method is called using an object/instance of the class. You
have to decide how you want to call the method: with the class or an
In your case, I would suggest that Square.count makes more sense in
English–you are asking for the “count of Squares”; where if you ask for
a.count, it is not really clear what that means–the "count of a’s?
(I know that I can also type “def Square.count” instead of “def
You can also use a third syntax:
class << self
They are all equivalent. The second syntax is probably the most common.
If you use that syntax(or the third syntax), then if you change your
class’s name, you don’t have to also change the names of the class