ruby 中 singleton class 和 singleton method 分別是什么
Singleton method
A method which belongs to a single object rather than to an entire class and other objects. 一個方法只屬于一個對象,而不是整個類和其他實(shí)例化對象。
firstObj = ClassMethods.new
secondObj = ClassMethods.new
def firstObj.singletonMethod
"Hi am a singlton method available only for firstObj"
end
firstObj.singletonMethod # "Hi am a singlton method available only for firstObj"
secondObj.singletonMethod #undefined method `singletonMethod' for #<ClassMethods:0x32754d8> (NoMethodError)
So this “singletonMethod” belongs only to the firstObj object and won’t be available for other objects of this class.
If you try to make the secondObj.singletonMethod Ruby will inform you that singletonMethod is an undefined method.
所以,singletonMethod 只屬于 firstObj,不能被這個類的其他實(shí)例化對象所調(diào)用。如果你想用 secondObj.singletonMethod 調(diào)用這個單例方法,ruby 會告訴你 singletonMethod 沒有定義
If you like to find all the singleton methods for a specific object, you can say objectname.singleton_methods In our case
如果你想找到一個特定對象的所有單例方法,你可以用 objectname.singleton_methods 。在我們的例子里面就是:
firstObj.singleton_methods => ["singletonMethod"]
secondObj.singleton_methods => []
To avoid throwing undefined method error when you try to access a singleton method with some other object
避免調(diào)用單例方法****拋出方法未定義的異常:
if secondObj.singleton_methods.include?("singletonMethod")
secondObj.singletonMethod
end
# 或
if secondObj.singleton_methods.include?( :singletonMethod )
secondObj.singletonMethod
end