使用module_function
定义模块函数与在Ruby中使用self.
定义模块函数相同吗?也就是说,它们是否都会导致实例和模块方法的创建?
答案 0 :(得分:4)
没有
module M1
def self.foo; end
end
module M2
module_function
def goo; end
end
M1.methods(false) #=> [:foo]
M1.instance_methods #=> []
M1.private_instance_methods #=> []
M2.methods(false) #=> [:goo]
M2.instance_methods #=> []
M2.private_instance_methods #=> [:goo]
答案 1 :(得分:2)
self.
只创建模块方法,而module_function
创建模块和实例方法:
#!/usr/bin/env ruby
module M1
def self.foo
puts 'foo'
end
end
module M2
module_function
def foo
puts 'foo'
end
end
class C1
include M1
def test
puts 'Call M1 as module method:'
M1.foo
# puts 'Call M1 as instance method:'
# foo
end
end
class C2
include M2
def test
puts 'Call M2 as module method:'
M2.foo
puts 'Call M2 as instance method:'
foo
end
end
C2.new.test; C1.new.test
结果如下:
Call M2 as module method:
foo
Call M2 as instance method:
foo
Call M1 as module method:
foo
然后,如果您取消注释'调用M1作为实例方法:' 2行,您将看到此错误:
./m1.rb:24:in `test': undefined local variable or method `foo' for #<C1:0x007feb311767f8> (NameError)
这表明当方法定义为foo
时,实例方法self.foo
不。