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 中实现面向对象编程的核心概念。通过使用这些概念,您可以编写更易于理解和维护的代码。