Ruby - Create and use Class Methods

Introduction

Ruby class methods is like a static method in Java and C#.

A class method belongs to the class itself.

To define a class method, you must precede the method name with the class name and a full stop.

class MyClass 
   def MyClass.classMethod 
      puts( "This is a class method" ) 
   end 

   def instanceMethod 
      puts( "This is an instance method" ) 
   en 
end 

You should use the class name when calling a class method:

MyClass.classMethod 

A specific object cannot call a class method. Nor can a class call an instance method:

MyClass.instanceMethod   #=> Error! This is an 'undefined method' 
ob.classMethod           #=> Error! This is an 'undefined method' 

Related Topic