模块是一种类似于类的结构,但与类不同的是,模块不能创建实例,也不能定义子类。模块的主要用途是:
- 混合(Mixins):通过
include关键字将模块中的方法和常量引入到类中。 - 命名空间:模块可以用来组织相关的类,避免命名冲突。
- 常量定义:模块内部也可以定义常量。
模块的基本使用
创建模块
创建一个模块非常简单,只需要使用 module 关键字,然后指定模块的名字即可。
module MyModule # 模块的内容 end
包含模块
使用 include 关键字可以将模块中的方法引入到类中,从而扩展类的功能。
class MyClass include MyModule end
模块中的方法
模块中的方法可以在类中被调用,就像这些方法是类的一部分一样。
// www.javascriptcn.com code example
module MathOperations
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
end
class Calculator
include MathOperations
end
calc = Calculator.new
puts calc.add(5, 3) # 输出: 8
puts calc.subtract(5, 3) # 输出: 2模块作为命名空间
模块可以用来组织一组相关的类和模块,这有助于避免命名冲突,并且可以清晰地划分代码库。
// www.javascriptcn.com code example
module Shapes
class Circle
def initialize(radius)
@radius = radius
end
def area
Math::PI * @radius ** 2
end
end
class Rectangle
def initialize(width, height)
@width = width
@height = height
end
def area
@width * @height
end
end
end
circle = Shapes::Circle.new(5)
rectangle = Shapes::Rectangle.new(4, 6)
puts circle.area # 输出: 78.53981633974483
puts rectangle.area # 输出: 24模块中的常量
模块不仅可以包含方法,还可以包含常量。模块中的常量可以在模块外部通过模块名来访问。
// www.javascriptcn.com code example module Colors COLOR_RED = '红色' COLOR_BLUE = '蓝色' COLOR_GREEN = '绿色' end puts Colors::COLOR_RED # 输出: 红色 puts Colors::COLOR_BLUE # 输出: 蓝色 puts Colors::COLOR_GREEN # 输出: 绿色
模块中的类
模块内部也可以定义类,这样可以将相关的类放在同一个模块中。
// www.javascriptcn.com code example
module Animals
class Mammal
def breathe
puts "呼吸空气"
end
end
class Bird
def breathe
puts "呼吸空气"
end
def fly
puts "飞翔"
end
end
end
mammal = Animals::Mammal.new
bird = Animals::Bird.new
mammal.breathe # 输出: 呼吸空气
bird.breathe # 输出: 呼吸空气
bird.fly # 输出: 飞翔模块作为命名空间和方法的混合
模块常常同时作为命名空间和方法的混合来使用。这种方式使得代码更加有组织,也更容易维护。
// www.javascriptcn.com code example
module Geometry
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
def distance_to(other)
Math.sqrt((other.x - self.x)**2 + (other.y - self.y)**2)
end
end
module Operations
def self.add_points(p1, p2)
Geometry::Point.new(p1.x + p2.x, p1.y + p2.y)
end
end
end
point1 = Geometry::Point.new(0, 0)
point2 = Geometry::Point.new(3, 4)
puts point1.distance_to(point2) # 输出: 5.0
sum_point = Geometry::Operations.add_points(point1, point2)
puts sum_point.x # 输出: 3
puts sum_point.y # 输出: 4以上就是 Ruby 模块的基础介绍和一些常见用法。通过模块,你可以更好地组织和管理代码,提高代码的复用性和可维护性。