Exercise 2: On Class Methods

Practice using class variables and class methods.

Class methods

Like class variables, methods can be defined at the class level. Such methods are called class methods.

  • Class methods are defined by prepending the method name with self.. For example, in the following code snippet, greet is a class method.
class Person
 def self.greet()
  puts "Hello World!"
 end
end
  • The self keyword refers to the class itself. So, to call the class method, it has to be invoked on the class and not on a class instance. For example:
Press + to interact
puts Person.greet

Problem statement

Write a Counter class. It should have a count class method that displays the number of Counter objects created so far.

Example

With your definition, consider the following code:

  puts Counter.count
  
  Counter.new
  puts Counter.count

It’s expected to print:

0
1

Try it yourself

Press + to interact
# Write your code here