The main issue is that re-opening Dwa
and re-defining initialize
will replace the old initialize
. Since super
only works to reference to the superclass it is useless in this scenario.
To call the old behaviour, you'll have to store the old initialize
method somewhere and call it from the new definition. One way to do this would be to use instance_method
to grab and store the UnboundMethod
inside a variable. Then call it (using bind_call
) from the re-definition of initialize
.
# re-opening Dwa class
class Dwa
old_initialize = instance_method(:initialize)
define_method :initialize do
old_initialize.bind_call(self)
@nazwa = "trzy"
end
end
The reason we use define_method :initialize
here, instead of def initialize
, is because of the context switch. Using define_method :initialize
with a block allows us to access the outer old_initialize
variable, which is not possible with def initialize
.
Alternatively you could change the class structure/hierarchy and define a new class using Dwa
as its superclass instead.
class NewDwa < Dwa
def initialize
super
@nazwa = "trzy"
end
end