Ruby Programming – Classes – How to create class methods?

We have discussed an introduction to the Classes in Ruby in my previous Article “Ruby Programming – An Overview on Classes“. There we have seen defining classes and creating objects to the classes using class’s new method. And also discussed that, the classes have instance methods and class methods.

There are different ways we can create class methods in Ruby. We will discuss them through this Article.

Creating class methods using class Name

Class methods in Ruby can be created by prefixing the method name with the class name and the dot operator. For example, to define a class method  “PrintMe” for a class “Sample”; the syntax looks like below;

def Sample.PrintMe
   # method definition here
end

Using self keyword to create class methods

Another way of creating a class method in Ruby is by prefixing the method name with self keyword and the dot operator. For example, to create a “PrintMe_2” class method for the “Sample” class; the syntax looks like below;

def self.PrintMe_2
   # definition of the method goes here
end

class << self syntax to create class methods

If you want to create multiple class methods; instead of the prefixing the method name either by class name or self keyword with dot operators; you can use class << self syntax to group all the class methods in one place. Inside this group; you can define the methods as normal way; like instance method declarations. Here is the example, where all the class methods can be grouped using this syntax;

class << self
   def PrintMe_3
      # method definition
   end
   def PrintMe_4
      # method definition
   end
end

Note that, you can call class methods using class names only; not through class instances or objects.

Finally, putting altogether; here is the working example.

class Sample
  def Sample.PrintMe
    puts "class method creation using class name."
  end
  
  def self.PrintMe_2
    puts "class method creation using self keyword"
  end
  
  class << self
    def PrintMe_3
      puts "class methods using class << self syntax"
    end
    
    def PrintMe_4
      puts "class methods using class << self syntax"
    end
  end
end

Sample.PrintMe
Sample.PrintMe_2
Sample.PrintMe_3
Sample.PrintMe_4

| Nick |

Add a Comment

Your email address will not be published.