【发布时间】:2014-02-12 19:23:24
【问题描述】:
我是动态类型编程语言的新手,我遇到了继承问题。 就我而言,我学习了 Ruby 课程:
class Vertex
def initialize(given_object, *edges)
@o = given_object
@e = edges
end
end
我需要为对象类扩展 Vertex 类,
class Vertex < given_object
所以我需要从构造函数中给出的对象扩展我的对象
我知道这是基本知识,但正如我之前提到的,我是动态类型语言的新手。
@已编辑: 好的,我明白了,让我们考虑这个例子:
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}
但我得到了解释器错误
`<top (required)>': undefined method `each' for #<TestClass:0x00000001275960 @object=[1, 2, 3, 4, 5, 6, 7, 8, 9]> (NoMethodError)
【问题讨论】:
-
不是
def Vertex,而是class Vertex。 -
Mazeryt,重新编辑。您尚未为
TestClass定义方法each并且未为其任何祖先定义each:TestClass.ancestors => [TestClass, Object, PP::ObjectMixin, Kernel, BasicObject]。因此,未定义的错误异常。您使用class关键字定义TestClass。TestClass < object.class在这里是TestClass < Array,它告诉你TestClass是否是Array的子类;它不会改变TestClass的出身。在这里它返回nil。见Module#<。
标签: ruby dynamic-typing