15、Ruby 编程:类变量、类方法、类常量、模块与命名空间

Ruby 编程:类变量、类方法、类常量、模块与命名空间

1. 类变量

在 Ruby 中,除了实例变量(以 @ 开头,与类的实例相关联),类还可以使用类变量(以 @@ 开头)。类变量与类本身相关联,而不是与类的特定实例相关联。类变量可以在任何方法定义之外赋值,并且可以被任何方法使用。

1.1 使用类变量的示例

以下是一个使用类变量来跟踪 Pet 类及其子类对象总数的示例:

# Script 8.5 - pets3.rb

# Define the Pet class:
class Pet
  # Class variable:
  @@count = 0

  # Getter for the name:
  attr_reader :name

  # Constructor sets the pet’s name
  # and increments the count:
  def initialize(name)
    @name = name
    @@count += 1
  end

  # Returns the total number of pets:
  def total_pets
    @@count
  end
end # End of Pet definition.

# Dog class is an extension of Pet:
class Dog < Pet
end

# Cat class is an extension of Pet:
class Cat 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值