I learning ruby singletons and have misunderstanding with such code:
class MyClass
def self.class_singleton_mymethod
end
end
class_singleton = class << MyClass
self
end
puts class_singleton.methods.grep(/mymethod/) # => []
obj = MyClass.new
def obj.object_singleton_mymethod
end
object_singleton = class << obj
self
end
puts object_singleton.methods.grep(/mymethod/) # => class_singleton_mymethod
Why class_singleton not contains class’s Class method and object_singleton instead of Object’s singleton method contains class’s Class method?
I think you have the notion of
methodsandinstance_methodsmixed up. If you were to replace all instances ofmethodswithinstance_methods, you will see the results you expect.instance_methodsis used to enumerate which methods a class’s instances have.methodsis used to enumerate what methods the object has. (Class objects are objects too, and have their own methods likenewthat are not instance methods.For example,
String#sliceis an instance method; you can callsliceon string instances. On the other hand,String.newis a method onStringitself; you don’t callnewon string instances, but you can callString.new(i.e., on theStringclass object itself) to create a new string.)