Ruby - Create and use Class Methods


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" ) 

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

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


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