Rpant Rpant - 5 months ago 9
Ruby Question

Keepinig Ruby OOP DRY

I am relatively new to ruby. Is it possible that initializing an object will automatically initialize its parent class? I know you can call super manually to call the superclass' initialize method, but does this happen automatically if you do not explicitly call super?

In java it happens. When you initialize a java object its parent class' objects are automatically initialized and its parent class' constructors are automatically called.

If this does not happen in ruby, does it mean a new parent class object is not automatically created (initialized) along with child class?

If that's the case, what would be the best OOP way to solve my problem?

Class B is a child of A. A has an attribute Xresult. B's initialize is passed object X and we need to set Xresult in A by using the object X passed to B's initialize.

One way would be to pass X to A's initialize where we can get Xresult out of X and set the attribute. However to do that I will have to do a super(X) in B's initialize. This won't be dry. I have many B like children.

Answer

but does this happen automatically if do not explicitly call super.

No, it doesn't happen automatically if the subclass has its own initialize method. However, if the subclass doesn't define its own initialize method, then it will inherit the one from the parent class.

One way would be to pass X to A's initialize where we can get Xresult out of X and set the attribute. However to do that i will have to do a super(X) in B's initialize. ( This wont be dry. I have many B like childs )

I think that this is a perfectly acceptable solution. Duplicating a single line of code like super x is unavoidable.


That being said, you could just have A's initialize method call a method that you define in B like so:

class A
  def initialize(x)
    @x = x
    initialize_subclass if respond_to?(:initialize_subclass)
  end
end

class B < A
  def initialize_subclass
    puts 'doing B-specific stuff'
  end
end

B.new(5)
A.new(6)
Comments