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:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy