Search⌘ K

Exercise 2: On Class Methods

Explore how to define class methods using self in Ruby and understand their use by creating a Counter class to track instances. This lesson helps you grasp calling methods on classes instead of instances and managing class-level information.

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:
Ruby
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

Ruby
# Write your code here