bmck
bmck

Reputation: 765

Ruby Design Pattern Question - Classes/Modules Inheritance

Right now I have:

module A  
  class B
    def initialize
       @y = 'foo'
    end  
  end
end

module A   
  class C < B
    def initialize
       @z = 'buzz'
    end   
  end
end

How can I have it so when I instantiate C @y is still set equal to 'foo'? Do I have to repeat that in the initialize under C? I am a following a bad pattern? Should @y be a class variable or just a constant under the module? Any help would be appreciated!

Upvotes: 1

Views: 513

Answers (2)

Phrogz
Phrogz

Reputation: 303168

class A::C < B
   def initialize( x, y )
     super # With no parens or arguments, this passes along whatever arguments
           # were passed to this initialize; your initialize signature must
           # therefore match that of the parent class
     @z = 'buzz'
   end
end

Or, as @EnabrenTane pointed out, you can explicitly pass along whatever arguments you know the super class will be expecting.

For more on inheritance, see the section on Inheritance and Messages in the old-but-free online version of the Pickaxe book.

Upvotes: 3

EnabrenTane
EnabrenTane

Reputation: 7466

You need the super keyword. It calls your parents definition of the same method.

I added params just in case. Note, to pass params B#initialize will have to take optional params as well.

module A   
  class C < B
    def initialize(params = nil)
       super(params) # calls B#initialize passing params
       @z = 'buzz'
    end   
  end
end

Upvotes: 2

Related Questions