子類
繼承允許類根據現有類定義特定行為。
class Animal
def say_hello
'Meep!'
end
def eat
'Yumm!'
end
end
class Dog < Animal
def say_hello
'Woof!'
end
end
spot = Dog.new
spot.say_hello # 'Woof!'
spot.eat # 'Yumm!'
在這個例子中:
Dog繼承自Animal,使其成為一個子類。Dog從Animal獲得了say_hello和eat方法。Dog覆蓋了具有不同功能的say_hello方法。