Ruby - Class Methods vs. Object Methods

Introduction

Consider the following code

class Square 
  def initialize(side_length) 
    @side_length = side_length 
  end 

  def area 
    @side_length * @side_length 
  end 
end 

The area method is made available in all objects of class Square, so it's considered to be an object method.

Here's a simple demonstration of a class method:

Demo

class Square 
  def self.test_method #class method
    puts "Hello from the Square class!" 
  end # from  w  w w .  jav a  2  s  . c o  m
  def test_method      #instance method
    puts "Hello from an instance of class Square!" 
  end 
end 

Square.test_method 
Square.new.test_method

Result

Here, Square class has two methods.

The first is a class method, and the second is an instance method.

They both have the same name of test_method.

The class method is denoted with self where self represents the current class.

def self.test_method defines the method as being specific to the class.

With no prefix, methods are automatically instance methods.

Alternatively, you could define the method like so:

class Square 
  def Square.test_method 
    puts "Hello from the Square class!" 
  end 
end 

The style ClassName.method_name versus self.method_name comes down to personal preference.

Related Topics