class variable in ruby

类变量,用@@开头.可以被子类或子类的实例使用。类似全局变量,不推荐使用,通常使用类实例变量替代。

class HelloCount
  @@count = 0

  def HelloCount.count
    @@count
  end

  def initialize(myname="Ruby")
    @name = myname
  end

  def hello
    @@count += 1
    puts "Hello, world, I am #{@name}"
  end

end


bob = HelloCount.new("Bob")
alice = HelloCount.new("Alice")
ruby = HelloCount.new


p HelloCount.count

bob.hello
alice.hello
ruby.hello

p HelloCount.count