Ruby - Singleton Class Methods

Introduction

You can create class methods by appending a method name to the name of the class like this:

def MyClass.classMethod

There is a "shortcut" syntax for doing this. Here is an example:

class MyClass
   def MyClass.methodA
      puts("a")
   end
   class << self
      def methodB
         puts("b")
      end
      def methodC
         puts("c")
      end
   end
end

Here, methodA, methodB, and methodC are all class methods of MyClass; methodA is declared using the syntax used previously:

def ClassName.methodname

methodB and methodC are declared using the syntax of instance methods:

def methodname

The following code turns the declarations to class methods:

class << self
    # some method declarations
end

You can add singleton methods from outside the class definition by using << followed by the class name, like this:

class << MyClass
   def methodD
      puts( "d" )
   end
end

Finally, the code checks that all four methods really are singleton methods by first printing the names of all available singleton methods and then calling them:

Demo

class MyClass
   def MyClass.methodA
      puts("a")#   w  w w  .  j a  v  a  2s.co  m
   end
   class << self
      def methodB
         puts("b")
      end
      def methodC
         puts("c")
      end
   end
end

class << MyClass
   def methodD
      puts( "d" )
   end
end

puts( MyClass.singleton_methods.sort )
MyClass.methodA
MyClass.methodB
MyClass.methodC
MyClass.methodD

Result

Related Topic