The singleton methods of an object are not defined by the class of that object. But they are methods and they must be associated with a class of some sort. The singleton methods of an object are instance methods of the anonymous singleton-class(eigenclass) associated with that object.
To open the singleton-class of the object obj
, use class << obj
class Object
# Get the singleton-class object of a class object.
def singleton_class
class << self #Open the singleton-class of `self`
# When you open the singleton-class of an object,
# `self` refers to the anonymous singleton-class object.
self
end
end
end
class Foo
# Define singleton-method
def self.singleton_method_1
end
# Another way to define singleton-method
class << self
def singleton_method_2
end
end
def instance_method_1
end
a = p self.singleton_class.instance_methods(false) # => [:singleton_method_1, :singleton_method_2]
b = p self.methods(false) # => [:singleton_method_1, :singleton_method_2]
# So called 'class methods' are just the instance methods of it's associated singleton-class.
p a==b # => true
end