1

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)
Mazeryt
  • 855
  • 1
  • 18
  • 37
  • 1
    It is not `def Vertex`, rather `class Vertex`. – Arup Rakshit Feb 12 '14 at 19:25
  • Mazeryt, re your edit. You have not defined the method `each` for `TestClass` and `each` is not defined for any of its ancestors: `TestClass.ancestors => [TestClass, Object, PP::ObjectMixin, Kernel, BasicObject]`. Hence, the undefined error exception. You define `TestClass` with the `class` keyword. `TestClass < object.class` is here `TestClass < Array`, which tells you whether `TestClass` is a subclass of `Array`; it does not change the parentage of `TestClass`. Here it returns `nil`. See [Module#<](http://ruby-doc.org/core-2.1.0/Module.html#method-i-3C). – Cary Swoveland Feb 12 '14 at 22:06

3 Answers3

1

Unfortunately, you can't alter an object's superclass at runtime.

See How to dynamically alter inheritance in Ruby for some alternate ideas that may work for you.

Community
  • 1
  • 1
1

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}
mikdiet
  • 9,859
  • 8
  • 59
  • 68
0

The def keyword is used for methods, not classes. Try using class vertex and see if your issue is resolved.

Andrew Backes
  • 1,884
  • 4
  • 21
  • 37