定义模块
module MyModule
def my_method
puts "This is a method in MyModule"
end
end
使用模块中的方法
class MyClass
include MyModule
def another_method
puts "This is another method in MyClass"
end
end
obj = MyClass.new
obj.my_method # 调用模块中的方法
obj.another_method # 调用类中的方法
在上面的例子中,MyModule 中的 my_method 方法被包含(include)到了 MyClass 中,因此 MyClass 的实例可以调用 my_method 方法。
命名空间
模块也可以用于创建命名空间,防止命名冲突:
module MathOperations
def self.square(num)
num * num
end
end
module StringOperations
def self.reverse(str)
str.reverse
end
end
puts MathOperations.square(5) # 调用模块中的方法
puts StringOperations.reverse("hello") # 调用另一个模块中的方法
在这个例子中,MathOperations 和 StringOperations 是两个独立的模块,它们各自包含了一些方法,这样可以避免全局命名空间中的冲突。
总的来说,模块是 Ruby 中一个强大而灵活的特性,用于组织和管理代码,防止命名冲突,并实现代码的重用。
转载请注明出处:http://www.zyzy.cn/article/detail/13430/Ruby