我有一个名为LibraryItem
的Ruby类。我想将此类的每个实例与一个属性数组关联起来。这个数组很长,看起来像这样:
['title', 'authors', 'location', ...]
请注意,这些属性实际上不应该是方法,而只是一个LibraryItem
拥有的属性列表。接下来,我想创建一个
LibraryItem
子类,名为LibraryBook
,它具有一个属性数组,其中包括LibraryItem
的所有属性,但也将包括更多属性。最终,我希望有几个
LibraryItem
的子类,每个子类都有自己版本的@attributes
数组,但每个子类都添加到LibraryItem
的@attributes
中(例如LibraryBook
,LibraryDVD
,LibraryMap
等)。所以,这是我的尝试:
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建议的方法)。
虽然这肯定可以工作(事实上,这就是我一直在做的),但我对此不太满意,因为它是次优的:为什么每次创建对象时都要构造这些不变的数组呢?
我真正想要的是具有继承自父类的类变量,但当在子类中更改时,不会在父类中更改。