3. 单例方法

单例方法(singleton method)是添加到单个对象的方法,不能被其他对象使用。单例方法可以通过将方法名称附加到对象名称后跟一个点或者通过将“普通”(normal)方法定义放在 <ObjectName> << self 块中来定义,如下所示:

  1. # create object
  2. ob = MyClass.new
  3. # define a singleton method
  4. def ob.singleton_method1
  5. puts( "This is a singleton method" )
  6. end
  7. # define another singleton method
  8. class << ob
  9. def singleton_method2
  10. puts( "This is another singleton method" )
  11. end
  12. end
  13. # use the singleton methods
  14. ob.singleton_method1
  15. ob.singleton_method2