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
超级会员免费看
订阅专栏 解锁全文
83

被折叠的 条评论
为什么被折叠?



