Ruby 中的 module_function 和 extend self异同(rubysmb error)居然可以这样

随心笔谈2年前发布 admin
187 0 0

文章摘要

这篇文章主要介绍了Ruby模块系统中不同方法调用的基本规则和操作。文章重点讲解了模块方法(module method)、私有方法(private method)以及如何将私有方法绑定到模块函数(module_function)。通过示例代码,展示了如何在模块中定义这些方法,以及在模块外类中包含模块后,如何通过实例调用这些方法。 文章的核心内容可以概括为: 1. 模块方法(module_method)可以被模块直接调用,但不能通过对象调用。 2. 私有方法(private method)需要通过绑定到模块函数(module_function)的方式来调用,否则无法通过对象调用。 3. 当试图调用无法被调用的模块方法或私有方法时,会抛出NoMethodError,并给出相应的错误提示。 文章通过代码示例详细演示了这些规则的应用场景,帮助读者理解模块化编程中方法调用的灵活性和限制。


# test.rb
module MyModule
def public_meth
p “a public method, if the module is included to a class , can be call as object.public_meth”
end
def module_method
p “a module method,can be called as module_name.module_method. but can not be call as object.module_method”
end
private
def private_method_to_module_function
p “a private_method, but can be call as module_name.module_method, because it was assigned to module_function”
end
def private_method
p “I am a private method”
end
module_function :module_method, :private_method_to_module_function
end

MyModule.module_method
MyModule.private_method_to_module_function
begin
MyModule.public_meth
rescue
p “public method can not be called by module_name.public_meth”
end
begin
MyModule.private_method
rescue NoMethodError
p “private method can not be called by module_name.module_method”
end

class MyClass
include MyModule
end

obj=MyClass.new
obj.public_meth

begin
obj.private_method
rescue NoMethodError
p “private method in module can not be call by object.method_name”
end

begin
obj.module_method
rescue NoMethodError
p “module method can not be called by object.method_name, for object, module method is private instance method”
end

#调用
ruby test.rb
“a module method,can be called as module_name.module_method. but can not be call as object.module_method”
“a private_method, but can be call as module_name.module_method, because it was assigned to module_function”
“public method can not be called by module_name.public_meth”
“private method can not be called by module_name.module_method”
“a public method, if the module is included to a class , can be call as object.public_meth”
“private method in module can not be call by object.method_name”
“module method can not be called by object.method_name, for object, module method is private instance method”

© 版权声明

相关文章