Class methods give you the mechanism to properly implement the object counter : Class Methods « Class « Ruby






Class methods give you the mechanism to properly implement the object counter


class Square
  def initialize
    if defined?(@@number_of_squares)
      @@number_of_squares += 1
    else
      @@number_of_squares = 1
    end
  end

  def Square.count
    @@number_of_squares
  end
end

a = Square.new
puts Square.count
b = Square.new

puts Square.count
c = Square.new
puts Square.count

 








Related examples in the same category

1.Creating Class Methods
2.The area method is made available in all objects of class Square,
3.Static class method