Home > Net >  Ruby Inheritance Puzzle: How to Properly Call self.class.new in Parent Method
Ruby Inheritance Puzzle: How to Properly Call self.class.new in Parent Method

Time:01-06

I have a library that I would use in an app by using a class that wraps the library object in a new class by inheriting from it and adding a few instance variables. I can change the library code if need be. Here is the problem:

class A
  def process_it
    # Make a new instance
    aa = self.class.new
    do_something_to(aa)
  end

  def do_something_to(item)
    item
  end
end

class B < A
  def initialize(extra = "Default extra")
    @extra = extra
    super()
  end

  def extra
    @extra
  end
end

# I want B to inherit A's methods, like #process_it but:
b = B.new("Non-default extra")
puts b.process_it.extra => Default extra

The output should have been "Non-default extra" and the problem is that, in the parent class I call self.class.new but can pass no parameter to it to set @extra. In the call, self.class is B, the inherited class, but when I write the parent class library, A, I cannot predict what, if any parameters, should be passed to self.class.new. Indeed, I might have class C < A with different parameters for initialize.

Is there a proper way to write the code in library A to instantiate a new instance of the self class that takes possible parameters into account?

CodePudding user response:

Will #dup work for you? Instead of aa = self.class.new, change it to aa = self.dup

  •  Tags:  
  • Related