1. Ruby 面向对象编程基础Ruby 是一门纯面向对象的编程语言这意味着在 Ruby 中一切皆为对象包括数字、字符串甚至类本身。这种设计理念使得 Ruby 代码具有极高的表达力和灵活性。与 Java 或 C 这类静态类型语言不同Ruby 采用动态类型系统不需要显式声明变量类型让开发者能够更专注于业务逻辑的实现。在 Ruby 中每个对象都是某个类的实例。例如数字 5 是 Fixnum 类的实例hello 是 String 类的实例。你可以通过调用对象的 class 方法来查看它所属的类5.class # Integer hello.class # StringRuby 的面向对象特性包括封装、继承和多态这三大支柱。封装通过将数据和操作数据的方法绑定在一起隐藏内部实现细节继承允许创建层次化的类结构子类可以复用父类的行为多态则让不同类的对象能够响应相同的方法调用。2. 类与对象的创建和使用2.1 定义类与实例化对象在 Ruby 中使用 class 关键字定义类类名采用大驼峰命名法CamelCase。下面是一个简单的 Person 类定义class Person def initialize(name, age) name name age age end def introduce Hi, Im #{name} and Im #{age} years old. end endinitialize 方法是 Ruby 中的构造方法当调用 new 方法创建对象时会自动执行。实例变量以 开头如 name 和 age它们的作用域是整个实例。创建 Person 对象并调用方法person Person.new(Alice, 30) puts person.introduce # 输出: Hi, Im Alice and Im 30 years old.2.2 访问控制与封装Ruby 提供了三种访问控制级别public默认级别方法可以在任何地方被调用protected只能在类内部或其子类中被调用private只能在类内部被调用且不能显式指定接收者示例class BankAccount def initialize(balance) balance balance end def deposit(amount) balance amount log_transaction(deposit, amount) end def withdraw(amount) balance - amount log_transaction(withdraw, amount) end private def log_transaction(type, amount) puts #{type} #{amount} at #{Time.now} end end在这个例子中log_transaction 方法被声明为 private只能在类内部被调用。3. 继承与模块3.1 类继承Ruby 支持单继承使用 符号表示继承关系class Employee Person def initialize(name, age, position) super(name, age) position position end def introduce #{super} I work as a #{position}. end endsuper 关键字用于调用父类的同名方法。在上面的例子中Employee 类继承了 Person 类并扩展了 introduce 方法。3.2 模块与混入Ruby 通过模块Module实现多重继承的功能。模块是一组方法和常量的集合可以被混入mixin到类中module Swimmable def swim I can swim! end end class Fish include Swimmable end class Dog include Swimmable endinclude 关键字将模块的方法作为实例方法混入类中。Ruby 还提供了 extend 关键字用于将模块的方法作为类方法混入。4. Ruby 特有的面向对象特性4.1 开放类与猴子补丁Ruby 的类在定义后仍然可以被重新打开和修改这种特性称为开放类Open Class。利用这个特性我们可以为现有类添加或修改方法class String def shout #{self.upcase}!!! end end hello.shout # HELLO!!!这种在运行时修改已有类的技术被称为猴子补丁Monkey Patching。虽然强大但应谨慎使用因为它可能带来意外的副作用。4.2 方法缺失与动态方法Ruby 提供了 method_missing 机制当调用不存在的方法时会触发这个方法class DynamicProxy def method_missing(method_name, *args, block) Called #{method_name} with #{args.inspect} end end proxy DynamicProxy.new proxy.undefined_method(1, 2, 3) # Called undefined_method with [1, 2, 3]结合 define_method我们可以动态地创建方法class DynamicCreator [:foo, :bar, :baz].each do |name| define_method(name) do Dynamic #{name} end end end4.3 元编程能力Ruby 强大的元编程能力使其面向对象特性更加灵活。例如我们可以使用 class_eval 和 instance_eval 在运行时修改类和对象class MyClass; end MyClass.class_eval do def instance_method New instance method end end obj MyClass.new obj.instance_method # New instance method5. Ruby 面向对象的最佳实践5.1 单一职责原则每个类应该只有一个职责这有助于保持代码的清晰和可维护性。例如将用户认证逻辑和数据持久化逻辑分离到不同的类中class UserAuthenticator def authenticate(email, password) # 认证逻辑 end end class UserRepository def save(user) # 保存逻辑 end end5.2 组合优于继承优先使用组合而非继承来复用代码。这可以通过模块混入或对象组合实现module Persistable def save # 保存逻辑 end end class User include Persistable def initialize(logger) logger logger end def log_action(action) logger.log(action) end end5.3 鸭子类型Ruby 推崇鸭子类型Duck Typing——如果它走起来像鸭子叫起来像鸭子那么它就是鸭子。这意味着我们更关注对象能响应什么方法而不是它属于什么类def print_items(items) items.each { |item| puts item.to_s } end # 可以传入任何实现了 each 方法的对象 print_items([1, 2, 3]) print_items({a: 1, b: 2})5.4 防御性编程在 Ruby 中由于动态类型特性防御性编程尤为重要。可以使用 respond_to? 检查对象是否能响应特定方法def process(obj) if obj.respond_to?(:process) obj.process else raise ArgumentError, Object must respond to :process end end6. Ruby 面向对象的高级主题6.1 单例类与类方法每个 Ruby 对象都有一个隐藏的单例类singleton class用于存储该对象特有的方法。类方法实际上就是存储在类的单例类中的方法class MyClass def self.class_method This is a class method end end # 等价于 class MyClass class self def class_method This is a class method end end end6.2 方法查找路径当调用一个方法时Ruby 会按照以下顺序查找对象的单例类中的方法混入的模块中的方法后 include 的模块优先父类中的方法继续向上查找直到 BasicObject可以使用 ancestors 方法查看类的继承链class A; end class B A; end B.ancestors # [B, A, Object, Kernel, BasicObject]6.3 对象空间与垃圾回收Ruby 使用标记-清除Mark-and-Sweep算法进行垃圾回收。理解对象引用关系有助于避免内存泄漏# 创建循环引用 class Node attr_accessor :next end a Node.new b Node.new a.next b b.next a # 即使外部不再引用 a 和 b它们也不会被回收7. Ruby 面向对象在实际项目中的应用7.1 Rails 中的 ActiveRecordRails 的 ActiveRecord 是 Ruby 面向对象的经典应用。每个模型类继承自 ActiveRecord::Base通过元编程动态添加了大量方法class User ActiveRecord::Base has_many :posts validates :email, presence: true end # 自动生成的类方法和实例方法 User.find(1) # 类方法 user.posts # 实例方法7.2 设计模式实现许多设计模式在 Ruby 中有简洁的实现方式。例如观察者模式module Observable def add_observer(observer) observers || [] observers observer end def notify_observers(message) observers.each { |o| o.update(message) } if observers end end class Publisher include Observable def publish(message) notify_observers(message) end end7.3 领域特定语言DSLRuby 的面向对象特性使其非常适合创建内部 DSL。例如一个配置 DSLclass ConfigBuilder def initialize config {} end def database(block) config[:database] DatabaseConfig.new.tap { |db| db.instance_eval(block) } end def build config end end class DatabaseConfig attr_accessor :adapter, :host, :username, :password def method_missing(name, *args) if name.to_s.end_with?() send(name, *args) else super end end end config ConfigBuilder.new.database do adapter postgresql host localhost username user password secret end.build