要深入理解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面向對象編程。