Ruby class instance variables and inheritance

前端 未结 9 618
日久生厌
日久生厌 2020-12-28 08:02

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 lik

相关标签:
9条回答
  • 2020-12-28 08:55

    Just as a version:

    class LibraryItem < Object
      def initialize
        @attributes = ['one', 'two'];
      end
    end
    
    class LibraryBook < LibraryItem
      def initialize
       super
       @attributes.push('three')
     end
    end
    
    b = LibraryBook.new
    
    0 讨论(0)
  • 2020-12-28 08:59

    Since you mention that the attributes are "fixed" and "unchanging", I am assuming that you mean that you will never change their value once the object is created. In that case, something like the following should work:

    class Foo
        ATTRS = ['title', 'authors', 'location']
        def attributes
            ATTRS
        end
    end
    
    class Bar < Foo
        ATTRS = ['ISBN', 'pages']
        def attributes
            super + ATTRS
        end
    end
    

    You are manually implementing a reader method (instead of letting attr_accessor create it for you) that disguises the internal name of the array. In your subclass, you simply call the ancestor class' reader function, tack on the additional fields associated with the child class, and return that to the caller. To the user, this appears like a read-only member variable named attributes that has additional values in the sub-class.

    0 讨论(0)
  • 2020-12-28 08:59

    Out of curiosity, will something like this work?

    class Foo
      ATTRIBUTES = ['title','authors','location']
    end
    
    class Bar < Foo
      ATTRIBUTES |= ['ISBN', 'pages']
    end
    

    This would seem to produce the desired result - the ATTRIBUTES array is expanded when the class object is created, and the values of ATTRIBUTES varies as expected:

    > Foo::ATTRIBUTES
    => ['title','authors','location'] 
    > Bar::ATTRIBUTES
    => ['title','authors','location', 'ISBN', 'pages'] 
    
    0 讨论(0)
提交回复
热议问题