包含模块如何在类内与类外工作



在Ruby或Rails中,为什么"include"有时在类内,有时在类外?

我已经研究了上面的一个,但我无法理解的一件事是顶级include(即类体外部(如何将实例方法转换为类方法

例如:

module Human
def living
true
end
end
include Human

现在,根据上面链接问题的答案,include使Human的方法可以从所有文件中访问(如果我错了,请纠正我(。

但是,既然living被定义为实例方法,为什么我可以将该方法作为类方法访问?

Human.living
#=> true

从另一个答案:

在任何类定义之外include Foo都会为Object的祖先添加Foo。[...]Foo的所有实例方法现在都可以在任何地方使用。

通过在顶层包含一个模块,您实际上是在说:

Object.include(Human)
# or
class Object
include Human
end

你缺少的是模块和类也是对象。

对象响应的方法来自其祖先,例如:

1.0.class.ancestors
#=> [Float, Numeric, Comparable, Object, Kernel, BasicObject]
'abc'.class.ancestors
#=> [String, Comparable, Object, Kernel, BasicObject]

或者,对于您的模块:

Human.class.ancestors
#=> [Module, Object, Kernel, BasicObject]

当您在顶层include Human时,它会将该模块添加到每个对象的祖先中:

include Human
1.0.class.ancestors
#=> [Float, Numeric, Comparable, Object, Human, Kernel, BasicObject]
#                                        ^^^^^
'abc'.class.ancestors
#=> [String, Comparable, Object, Human, Kernel, BasicObject]
#                                ^^^^^
Human.class.ancestors
#=> [Module, Object, Human, Kernel, BasicObject]
#                    ^^^^^

一些例子:

1.0.living   #=> true
'abc'.living #=> true
Float.living #=> true
Human.living #=> true

> 这个问题不是 100% 清楚,但如果你想像访问类的类方法(或你称之为 self 方法(一样访问它的方法,你可以在模块中使用extend self

没有extend self

module MyModule
def hi; puts "hi"; end
end
class MyClass
include MyModule
def say_something
MyModule.hi
end
end
MyClass.new.say_something # => NoMethodError: undefined method `hi' for MyModule:Module

extend self

module MyModule
extend self
def hi; puts "hi"; end
end
class MyClass
include MyModule
def say_something
MyModule.hi
end
end
MyClass.new.say_something # => hi

在此处了解更多信息 Ruby:扩展自我

最新更新