Ruby 支持单继承(<)——一个类从一个超类继承。当你调用一个方法时,Ruby 在定义明确的方法查找路径(祖先链,包括混入的模块)中搜索它。理解这个路径解释了继承和 mixin 如何解析方法。
单继承
ruby
() = = name
=
<
.new().speak
.new().fetch
子类(Dog < Animal)继承超类的方法和实例变量,并可以覆盖方法。super 调用父类的版本。
class Dog < Animal
def initialize(name, breed)
super(name) # call Animal#initialize
@breed = breed
end
def speak
super + " (woof)" # super (no parens) passes the same args; here calls Animal#speak
end
end
# Ruby searches for a method in this ORDER (the ancestors chain):
Dog.ancestors
# => [Dog, <included modules>, Animal, <Animal's modules>, Object, Kernel, BasicObject]
# lookup: the class itself → its included MODULES (last included first) →
# the superclass → ITS modules → ... up to BasicObject
当你调用一个方法时,Ruby 遍历祖先链(Class.ancestors):类本身,然后是它包含的模块(mixin——最近包含的优先),然后是超类及其模块,直到 BasicObject。第一个匹配获胜。这个单一路径解释了继承和 mixin 如何一起解析。
module Swimmer
def move = "swimming"
end
class Fish < Animal
include Swimmer # Swimmer is inserted into the lookup path (before Animal)
end
# Fish.ancestors → [Fish, Swimmer, Animal, ...] — a module's methods come before the superclass's
理解继承和方法查找路径是 Ruby 的重要知识,用于设计类层次结构,尤其是理解当继承和 mixin 结合时 Ruby 如何解析方法。
Ruby 的单继承(<)通过