Ruby class instance variables and inheritance

Posted by rlandster on Stack Overflow See other posts from Stack Overflow or by rlandster
Published on 2010-05-02T06:22:12Z Indexed on 2010/05/02 6:27 UTC
Read the original article Hit count: 266

Filed under:
|
|

I have a Ruby class called LibraryItem. I want to associate with every instance of this class an array of attributes. This array is long and looks something like

['title', 'authors', 'location', ...]

Note that these attributes are not really supposed to be methods, just a list of attributes that a LibraryItem has.

Next, I want to make a subclass of LibraryItem called LibraryBook that has an array of attributes that includes all the attributes of LibraryItem but will also include many more.

Eventually I will want several subclasses of LibraryItem each with their own version of the array @attributes but each adding on to LibraryItem's @attributes (e.g., LibraryBook, LibraryDVD, LibraryMap, etc.).

So, here is my attempt:

class LibraryItem < Object
  class << self; attr_accessor :attributes; end
  @attributes = ['title', 'authors', 'location',]
end

class LibraryBook < LibraryItem
  @attributes.push('ISBN', 'pages']
end

This does not work. I get the error

undefined method `push' for nil:NilClass

© Stack Overflow or respective owner

Related posts about ruby

Related posts about instance-variables