Ruby - Summarizing Instance, Class, and Singleton Methods

Introduction

An instance method is declared inside a class definition and is intended for use by a specific object or "instance" of the class, like this:

Demo

class MyClass
    # declare instance method
    def instanceMethod
        puts( "This is an instance method" )
    end# from  w  w  w .  j  a  v  a2 s.  c  o  m
end

# create object
ob = MyClass.new
# use instance method
ob.instanceMethod

Result

A class method may be declared inside a class definition, in which case the method name may be preceded by the class name.

Or you can create class method by using a class << self block with a "normal" method definition.

A class method is intended for use by the class itself, not by a specific object, like this:

Demo

class MyClass
    # a class method#   w w w .j  av  a2 s  .c  om
    def MyClass.classmethod1
        puts( "This is a class method" )
    end

    # another class method
    class << self
        def classmethod2
             puts( "This is another class method" )
        end
    end
end

# call class methods from the class itself
MyClass.classmethod1
MyClass.classmethod2

Result

Singleton methods are methods that are added to a single object and cannot be used by other objects.

A singleton method may be defined by appending the method name to the object name followed by a dot or by placing a "normal" method definition inside an ObjectName << self block like this:

Demo

class MyClass
    # a class method#   w w w  .ja  v  a 2 s  . c om
    def MyClass.classmethod1
        puts( "This is a class method" )
    end

    # another class method
    class << self
        def classmethod2
             puts( "This is another class method" )
        end
    end
end

# create object
ob = MyClass.new

# define a singleton method
def ob.singleton_method1
    puts( "This is a singleton method" )
end

# define another singleton method
class << ob
    def singleton_method2
        puts( "This is another singleton method" )
    end
end

# use the singleton methods
ob.singleton_method1
ob.singleton_method2

Result

Related Topic