4

为什么以下代码按我预期的方式运行?我的印象是一个类只能有一个超类,并且在第一次定义该类时放置原始超类以外的东西会引发类型不匹配异常。

class Test
end

class MyTest < Test

  def run
    p 'my test'
  end
end

class MyTest < Object

  def run
    p 'redefine my test'
  end
end

MyTest.new.run

结果

redefine my test
4

2 回答 2

5

只有当第二个类声明继承自Object. 任何其他 MI 尝试都会抛出TypeError.

它也不会改变类的继承。所以即使在之后MyTest.superclass仍然存在Testclass MyTest < Object

我认为这是因为定义新类时Object的默认值。superclass文档

new(super_class=Object) → a_class

因此,当Object给出时,superclass 它在不匹配检查中被忽略,因为不知道Object是用户输入还是默认值。

于 2013-10-20T08:08:28.320 回答
3

绝不。Ruby 不支持MI(但将特征视为有用的替代方案)。

无论如何,这个类的重新定义是不明确的,并且会根据特定的 Ruby 实现产生不同的效果。当我运行给定的代码时,我得到“TypeError: superclass mismatch for class ..”(Ruby 1.9.2;在 1.9.3 中,错误出现延迟)。

如果有问题的代码没有导致这样的错误,MyTest.superclass请检查重新定义后超类的真正含义:注意#superclass返回单个类对象,而不是集合。

下面是一个反例,认为这种重新定义方案不会添加或指示 MI:

class A
   def a; "a"; end
end
class B
   def b; "b"; end
end
class C < A
end
# This may raise said TypeError, but if it does not then ..
class C < B
end
# .. either this will work
C.new.a
# .. /or possibly/ this will work
C.new.b
# If the redefinition added MI then /both/ would work.
# If such an implementation is found, please let me know!

(如果不引发所述 TypeError,我无法使上述工作正常进行。)

于 2013-10-20T05:39:25.933 回答