在Ruby中,继承是通过使用关键字<
来实现的。当一个类继承另一个类时,子类将继承父类的所有属性和方法。子类可以覆盖父类中的方法,也可以添加新的方法。
例如,下面是一个简单的示例,展示了如何在Ruby中实现继承:
class Animal
def speak
puts "I am an animal"
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
animal = Animal.new
animal.speak # Output: I am an animal
dog = Dog.new
dog.speak # Output: Woof!
在上面的示例中,Dog
类继承了Animal
类,并覆盖了Animal
类中的speak
方法。因此,创建一个Dog
对象并调用speak
方法时,输出的内容是"Woof!“而不是"I am an animal”。