要深入理解Ruby面向对象编程(OOP),您需要了解以下几个方面:
class
关键字创建类,使用new
方法创建对象。class Dog
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
def bark
puts "Woof!"
end
end
my_dog = Dog.new("Buddy", "Golden Retriever")
my_dog.bark
extends
关键字实现继承。class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
puts "I am an animal."
end
end
class Dog < Animal
def bark
puts "Woof!"
end
end
my_dog = Dog.new("Buddy")
my_dog.speak
my_dog.bark
attr_reader
和attr_writer
创建访问器和修改器方法。class Person
attr_reader :name, :age
def initialize(name, age)
@name = name
@age = age
end
def birthday
@age += 1
end
end
my_person = Person.new("Alice", 30)
puts my_person.name # 输出 "Alice"
puts my_person.age # 输出 30
my_person.birthday
puts my_person.age # 输出 31
def
关键字)和方法重载(使用initialize
方法的重载)实现多态。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"), Cat.new("Kitty")]
animals.each do |animal|
animal.speak
end
include
关键字将模块包含到类中。module Canine
def bark
puts "Woof!"
end
end
class Dog
include Canine
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
end
my_dog = Dog.new("Buddy", "Golden Retriever")
my_dog.bark
通过深入了解这些概念并在实际项目中应用它们,您将能够熟练掌握Ruby面向对象编程。