Ruby 是一種面向對象的編程語言,它的核心理念是讓代碼更加簡潔、易讀和可維護。在 Ruby 中,面向對象編程主要通過以下幾個方面來體現:
類和對象:
示例:
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.name # 輸出 "Buddy"
my_dog.breed # 輸出 "Golden Retriever"
my_dog.bark # 輸出 "Woof!"
封裝:
示例:
class BankAccount
attr_accessor :balance
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
@balance -= amount
end
end
繼承:
示例:
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
puts "I am an animal."
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
my_dog = Dog.new("Buddy")
my_dog.name # 輸出 "Buddy"
my_dog.speak # 輸出 "Woof!"
多態:
示例:
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
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
通過以上幾個方面的運用,Ruby 的面向對象編程可以幫助我們更好地組織和管理代碼,提高代碼的可維護性和可擴展性。