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 的面向对象编程可以帮助我们更好地组织和管理代码,提高代码的可维护性和可扩展性。