在模块上定义的实例方法:
module A
def foo; :bar end
end
似乎可以在包含该模块时作为该模块的模块方法调用:
include A
A.foo # => :bar
为什么会这样?
最佳答案
你在加入一个目标。
module A
def self.included(base)
puts base.inspect #Object
end
def foo
:bar
end
end
include A
puts A.foo # :bar
puts 2.foo # :bar
#puts BasicObject.new.foo #this will fail
还要注意,顶层对象
main
是特殊的;它既是对象的实例,又是对象的委托者。参阅http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/
关于ruby - 为什么在包含之后将实例方法称为模块方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18009011/