下面是一个超类/子类构造的例子:
C:\>irb --simple-prompt
>> class Parent
>> @@x = 10
>> end
=> 10
>> class Child < Parent
>> @@x = 12
>> end
=> 12
>> class Parent
>> puts "@@X = #{@@x}"
>> end
@@X = 12
=> nil并且上面也是understood.But,我想检查一下,当两个类分别定义为一个独立的类时,是否可能定义它们之间的上下级关系?
我尝试了下面的方法,但它不起作用。可能不是我尝试的方式:
C:\>irb --simple-prompt
>> class Parent
>> @@X = 10
>> end
=> 10
>> class Child
>> @@x = 15
>> end
=> 15
>> class Child < Parent
>> def show
>> p "hi"
>> end
>> end
TypeError: superclass mismatch for class Child
from (irb):7
from C:/Ruby193/bin/irb:12:in `<main>'
>>发布于 2013-05-30 10:14:06
在Ruby中声明类之后,您不能更改它的超类。但是,如果您希望包含类的特定行为,则可以使用模块对其进行扩展。
module Parent
def yell_at_kids
puts "Stop hitting your brother!"
end
end
class Child
def have_children
extend Parent
end
end
Child.new.have_children.yell_at_kids在这种情况下,Parent是一个可以包含或扩展到其他对象中的模块(比如这里的Child类的一个实例)。您不能用另一个类扩展一个类,但是可以用一个模块扩展一个类。
https://stackoverflow.com/questions/16826766
复制相似问题