Ruby 编程:类实例变量与模块命名空间的运用
1. 类变量与类实例变量
在 Ruby 编程中,当我们需要为类关联数据时,有类变量和类实例变量这两种选择。
1.1 类变量回顾
假设我们的 Document 类需要设置默认纸张大小,比如美国常用的信纸尺寸或几乎在其他地方都流行的 A4 尺寸。我们可以使用类变量来存储这个默认信息。类变量以两个 @ 开头,与类相关联,而不是与普通实例相关联。以下是增强后的 Document 类,使用类变量来跟踪默认纸张大小:
class Document
@@default_paper_size = :a4
def self.default_paper_size
@@default_paper_size
end
def self.default_paper_size=(new_size)
@@default_paper_size = new_size
end
attr_accessor :title, :author, :content
attr_accessor :paper_size
def initialize(title, author, content)
@title = title
@author = author
@content = content
@paper_size = @@default_paper_size
end
# Rest of the class omitted.
超级会员免费看
订阅专栏 解锁全文
1

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



