singleton class 和 singleton method

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。