ruby类的方法

上篇文章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}"

 

与上篇文章代码不同的地方以用黑体标出了~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值