Ruby 是一種面向對象的編程語言,它的核心概念包括類(Class)、對象(Object)、繼承(Inheritance)、封裝(Encapsulation)和多態(Polymorphism)。下面是如何在 Ruby 中實現這些概念的簡要說明:
class
關鍵字,后跟類名。例如:class Dog
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
def bark
puts "Woof!"
end
end
new
方法創建類的實例。例如:my_dog = Dog.new("Buddy", "Golden Retriever")
extends
關鍵字實現繼承。例如:class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
puts "I am an animal."
end
end
class Dog < Animal
attr_accessor :breed
def initialize(name, breed)
super(name)
@breed = breed
end
def bark
puts "Woof!"
end
end
attr_accessor
和 attr_reader
創建訪問器(getter)和只讀訪問器(getter)。例如:class Dog
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
end
self
關鍵字實現多態。例如:class Animal
def speak
puts "I am an animal."
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
class Cat < Animal
def speak
puts "Meow!"
end
end
animals = [Dog.new("Buddy", "Golden Retriever"), Cat.new("Whiskers", "Siamese")]
animals.each do |animal|
animal.speak
end
這將輸出:
Woof!
Meow!
這些示例展示了如何在 Ruby 中實現面向對象編程的核心概念。通過使用這些概念,您可以編寫更易于理解和維護的代碼。