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. 一个方法只属于一个对象,而不是整个类和其他实例化对象。

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,不能被这个类的其他实例化对象所调用。如果你想用 secondObj.singletonMethod 调用这个单例方法,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
避免调用单例方法****抛出方法未定义的异常:

if secondObj.singleton_methods.include?("singletonMethod")
  secondObj.singletonMethod
end


# 或
if secondObj.singleton_methods.include?( :singletonMethod )
  secondObj.singletonMethod
end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容