Ruby中的类变量与类方法

    首先,我们通过一个实例来观察类变量与类方法:

  1. class Square 
  2.   def initialize 
  3.     @@number_of_squares = define?(@@number_of_squares) ? @@number_of_squares + 1 : 1 
  4.   end 
  5.  
  6.   def self.test_method 
  7.     puts "Hello from the Square class!" 
  8.   end 
  9.  
  10.   def test_method 
  11.     puts "Hello from an instance of class Square!" 
  12. end 

    上面的代码中,number_of_squares用来记录类Square的实例个数,是类变量,它与对象变量的区别是,前面用两个@符号来标记。Square类中,第一个test_method是类方法,它与对象方法的区别是,它用self.前缀标示。这里self表示当前类,因此self.test_method定义的方法专用于该类。

    如果我们学过Java或C++,会发现类变量其实与Java或C++中的静态变量类似,而类方法与Java或C++中的静态方法类似。