Ruby 是一種面向?qū)ο蟮木幊陶Z言,它的核心理念是讓代碼更加簡潔、易讀和可維護(hù)。在 Ruby 中,面向?qū)ο缶幊讨饕ㄟ^以下幾個(gè)方面來體現(xiàn):
類和對象:
示例:
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!"
多態(tài):
示例:
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
通過以上幾個(gè)方面的運(yùn)用,Ruby 的面向?qū)ο缶幊炭梢詭椭覀兏玫亟M織和管理代碼,提高代碼的可維護(hù)性和可擴(kuò)展性。