Ruby类何时可以有多个超类

Ruby类何时可以有多个超类,ruby,class,inheritance,Ruby,Class,Inheritance,为什么下面的代码按我预期的方式运行?我的印象是,一个类只能有一个超类,而在第一次定义该类时放置原始超类以外的其他对象将引发类型不匹配异常 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 从来没有。Ruby不支持MI(但

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

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
从来没有。Ruby不支持MI(但将traits视为有用的替代方案)

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

如果所讨论的代码没有导致这样的错误,请检查
MyTest.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!
A类
DEFA;“a”;结束
结束
B类
def b;“b”;结束
结束
C类
(我无法在不引发上述TypeError的情况下实现上述功能。)

只有当第二个类声明从
对象继承时,它才适用于我(Ruby 1.9.2和1.9.3)。对MI的任何其他尝试都会抛出
类型错误

此外,它不会更改类的继承。所以
MyTest.superclass
即使在
classmytest

我认为这是因为定义新类时,
Object
是默认的
superclass
。从:


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

虽然在一般情况下是正确的,但OP的问题有点微妙。我怀疑@tihorn的答案在这里是正确的。
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!
new(super_class=Object) → a_class