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)
2
  • 1
    It is not def Vertex, rather class Vertex. Commented Feb 12, 2014 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#<. Commented Feb 12, 2014 at 22:06

3 Answers 3

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}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

3 Comments

Thanks I edited my question, can You look on edited?
The def keyword is used for methods, not functions.
@JörgWMittag Woops, you are right. Been doing too much functional programming lately :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.