【发布时间】:2010-05-02 06:22:12
【问题描述】:
我有一个名为 LibraryItem 的 Ruby 类。我想与这个类的每个实例关联一个属性数组。这个数组很长,看起来像
['title', 'authors', 'location', ...]
请注意,这些属性实际上并不应该是方法,只是LibraryItem 具有的属性列表。
接下来,我想创建一个名为 LibraryBook 的 LibraryItem 的子类,它有一个属性数组,其中包含 LibraryItem 的所有属性,但还会包含更多属性。
最终我会想要几个LibraryItem 的子类,每个子类都有自己的数组@attributes,但每个子类都添加到LibraryItem 的@attributes(例如,LibraryBook、LibraryDVD、@987654333 @ 等)。
所以,这是我的尝试:
class LibraryItem < Object
class << self; attr_accessor :attributes; end
@attributes = ['title', 'authors', 'location',]
end
class LibraryBook < LibraryItem
@attributes.push('ISBN', 'pages')
end
这不起作用。我收到错误
undefined method `push' for nil:NilClass
如果它可以工作,我想要这样的东西
puts LibraryItem.attributes
puts LibraryBook.attributes
输出
['title', 'authors', 'location']
['title', 'authors', 'location', 'ISBN', 'pages']
(2010 年 5 月 2 日添加)
对此的一种解决方案是使@attributes 成为一个简单的实例变量,然后在initialize 方法中为LibraryBoot 添加新属性(这是demas 在其中一个答案中提出的建议)。
虽然这肯定行得通(事实上,这也是我一直在做的事情),但我对此并不满意,因为它是次优的:为什么每次创建对象时都要构造这些不变的数组?
我真正想要的是拥有可以从父类继承但在子类中更改时不会在父类中更改的类变量。
【问题讨论】:
标签: ruby class instance-variables