Ruby Singleton methods for class and objects

Viewed 9737

I am learning Ruby Singletons and i found some ways to define and get list of Class and Object singleton methods.

Class Singleton Methods

Ways to define class singleton methods:

class MyClass

  def MyClass.first_sing_method
    'first'
  end

  def self.second_sing_method
    'second'
  end

  class << self
    def third_sing_method
      'third'
    end
  end

  class << MyClass
    def fourth_sing_method
      'fourth'
    end
  end
end

def MyClass.fifth_sing_method
  'fifth'
end

MyClass.define_singleton_method(:sixth_sing_method) do
  'sixth'
end

Ways to get list of class singletons methods:

#get singleton methods list for class and it's ancestors 
MyClass.singleton_methods

#get singleton methods list for current class only  
MyClass.methods(false)

Object Singleton Methods

Ways to define object singleton methods

class MyClass
end

obj = MyClass.new

class << obj
  def first_sing_method
    'first'
  end
end

def obj.second_sing_method
  'second'
end

obj.define_singleton_method(:third_sing_method) do
  'third'
end

Way to get list of object singleton methods

#get singleton methods list for object and it's ancestors  
obj.singleton_methods

#get singleton methods list for current object only
obj.methods(false)

Are there other ways to do this?

3 Answers
Related