Search code examples
rubydynamic-typing

Ruby How to inherit from object given in constructor


I'm new in dynamic typed programming languages, and I have problem with inheritance. In my case I had followed Ruby class:

class Vertex
  def initialize(given_object, *edges)
    @o = given_object
    @e = edges
  end
end

And I need to extend Vertex class for object class,

class Vertex < given_object

So I need to extends my object from object that is given in constructor

I know that is basic knowledge but as I mentioned earlier I'm totally new in dynamic typed languages.

@edited: Ok I understand, so lets consider this example:

class TestClass
  def initialize(object)
    @object = object
    TestClass < object.class
  end
end

#now In code I want to run each method on TestClass because it should inherit from Array
v = TestClass.new([1,2,3,4,5,6,7,8,9])    
v.each { |number| print number}

but I got interpreter error

 `<top (required)>': undefined method `each' for #<TestClass:0x00000001275960 @object=[1, 2, 3, 4, 5, 6, 7, 8, 9]> (NoMethodError)

Solution

  • You probably wish to use Decorator pattern, when all methods are proxied to given model:

    class TestClass
      def initialize(object)
        @object = object
      end
    
      def method_missing(method, *args, &block)
        @object.send(method, *args, &block)
      end
    end
    
    v = TestClass.new([1,2,3,4,5,6,7,8,9])    
    v.each { |number| print number}