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开发者_C百科'? 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!
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.
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
精彩评论