Ruby中的继承怎么实现

2024-05-07

Ruby中,实现继承主要通过定义一个类并将其设置为另一个类的子类来实现。例如:

class Animal
  def speak
    puts "I am an animal"
  end
end

class Dog < Animal
  def bark
    puts "Woof!"
  end
end

dog = Dog.new
dog.speak  # Output: I am an animal
dog.bark   # Output: Woof!

在上面的例子中,Animal类是基类,Dog类是继承自Animal类的子类。通过在子类中定义新的方法或覆盖父类的方法,可以实现对父类的继承和扩展。