Ruby include 方法
最后修改日期:2025 年 4 月 27 日
本教程讲解 Ruby 的 include 方法用于模块包含。include 方法将模块的功能混入类中。
include 方法将模块的方法添加为类的实例方法。这是 Ruby 共享行为的主要混入机制。
包含的模块成为类祖先链的一部分。它们的实例方法对所有实例都可用。多个 include 按顺序处理。
基本模块包含
这个简单的例子展示了如何在类中包含模块。模块的方法对类实例可用。
module Greeter
def greet
"Hello from module!"
end
end
class MyClass
include Greeter
end
obj = MyClass.new
puts obj.greet
Greeter 模块的 greet 方法对 MyClass 实例可用。include 语句实现了这一点。
多模块包含
一个类可以包含多个模块。在查找方法时,会按包含的倒序搜索(最后包含的,最先检查)。
module ModuleA
def identify
"From ModuleA"
end
end
module ModuleB
def identify
"From ModuleB"
end
end
class MyClass
include ModuleA
include ModuleB
end
obj = MyClass.new
puts obj.identify
ModuleB 的方法具有更高的优先级,因为它最后被包含。Ruby 在解析方法时按包含的倒序搜索模块。
祖先链中的包含模块
包含的模块出现在类的祖先链中。本例演示了如何检查继承层次结构。
module MyModule
def module_method
"Module method called"
end
end
class MyClass
include MyModule
end
puts MyClass.ancestors.inspect
obj = MyClass.new
puts obj.module_method
ancestors 方法显示了继承链中的 MyModule。这解释了实例方法是如何可用的。
继承中的模块包含
当一个类继承自另一个类时,它也继承所有包含的模块。本例展示了模块继承。
module SharedBehavior
def shared_method
"Available to all subclasses"
end
end
class Parent
include SharedBehavior
end
class Child < Parent
end
obj = Child.new
puts obj.shared_method
Child 类从其父类继承了 SharedBehavior。模块成为继承层次结构的一部分。
Extend 与 Include
虽然 include 添加实例方法,但 extend 添加类方法。本例对比了这两种方法。
module MyMethods
def say_hello
"Hello!"
end
end
class WithInclude
include MyMethods
end
class WithExtend
extend MyMethods
end
puts WithInclude.new.say_hello
puts WithExtend.say_hello
include 使方法对实例可用,而 extend 使方法对类本身可用。两者都有不同的用途。
包含 Kernel 模块
Ruby 的 Kernel 模块会自动包含在 Object 中。本例展示了如何访问内核方法。
class MyClass
# Kernel methods like 'puts' are already available
def use_kernel_method
puts "This is a Kernel method"
end
end
obj = MyClass.new
obj.use_kernel_method
像 puts 这样的常用方法来自 Kernel 模块。它们随处可用,因为 Object 包含了 Kernel。
条件模块包含
模块可以根据运行时因素有条件地包含。这允许灵活的行为组合。
module AdminFeatures
def admin_action
"Performing admin action"
end
end
class User
def initialize(is_admin)
@is_admin = is_admin
end
def check_admin
extend AdminFeatures if @is_admin
end
end
admin = User.new(true)
admin.check_admin
puts admin.admin_action if admin.respond_to?(:admin_action)
在这里,我们有条件地使用 extend 来添加管理员功能。respond_to? 检查可确保安全的方法调用。
来源
本教程通过实际示例涵盖了 Ruby 的 include 方法,展示了模块混入、继承和方法查找行为。
作者
列出 所有 Ruby 教程。