2. 类方法

在这两种情况下,类方法(class method)可以在类定义中声明:a)类名在方法名之前;b)class << self 块包含’普通’(normal)的方法声明。无论哪种方式,类方法都是由类本身使用,而不是由特定对象使用,如下所示:

  1. class MyClass
  2. # a class method
  3. def MyClass.classmethod1
  4. puts( "This is a class method" )
  5. end
  6. # another class method
  7. class << self
  8. def classmethod2
  9. puts( "This is another class method" )
  10. end
  11. end
  12. end
  13. # call class methods from the class itself
  14. MyClass.classmethod1
  15. MyClass.classmethod2