上篇文章ruby类的变量 最后在调用类变量的时候是用一个实例返回的,其实只要使用类的方法就可以直接调用类的变量,且不需要创建任何示例
我把代码修改为:
class Person
attr_reader :name, :cost
@@totalcost = 0
def Person.totalcost
@@totalcost
end
def initialize(name)
@name = name
@cost = 0
end
def pay(cost)
@cost += cost
@@totalcost += cost
end
end
nh = Person.new('Ninghuan')
spy = Person.new('Spy')
nh.pay(100)
spy.pay(200)
puts "#{nh.name} cost #{nh.cost}"
puts "#{spy.name} cost #{spy.cost}"
puts "Toatal cost: #{Person.totalcost}"
与上篇文章代码不同的地方以用黑体标出了~~~