“包含模块”和“包含模块”有什么区别?和“扩展模块”在鲁比?
可能的重复:
Ruby 中的 include 和 extends 有什么区别?< /a>
给定:
module my_module
def foo
...
end
end
问题 1
之间有什么区别:
class A
include my_module
end
和
class A
extend my_module
end
问题 2
foo
会被视为实例方法还是类方法? 换句话说,这相当于:
class A
def foo
...
end
end
或:
class A
def self.foo
...
end
end
?
Possible Duplicate:
What is the difference between include and extend in Ruby?
Given:
module my_module
def foo
...
end
end
Question 1
What is the difference between:
class A
include my_module
end
and
class A
extend my_module
end
Question 2
Will foo
be considered an instance method or a class method ?
In other words, is this equivalent to:
class A
def foo
...
end
end
or to:
class A
def self.foo
...
end
end
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我很久以前写过一篇关于此的博客文章
当您“包含”模块时,该模块将被包含,就好像方法是在包含它们的类中定义的一样,您可以说它将方法复制到包含类。
当您“扩展”模块时,您是在说“将此模块的方法添加到此特定实例”。当您在类定义中并说“扩展”时,“实例”就是类对象本身,但您也可以执行类似的操作(如上面我的博客文章中所示):
所以,它不完全是一个类方法,但是您称为“扩展”的“实例”的方法。当您在类定义中执行此操作并且其中的实例是类本身时,它“看起来像”类方法。
I wrote a blog posting about this a long time ago here.
When you're "including" a module, the module is included as if the methods were defined at the class that's including them, you could say that it's copying the methods to the including class.
When you're "extending" a module, you're saying "add the methods of this module to this specific instance". When you're inside a class definition and say "extend" the "instance" is the class object itself, but you could also do something like this (as in my blog post above):
So, it's not exactly a class method, but a method to the "instance" which you called "extend". As you're doing it inside a class definition and the instance in there is the class itself, it "looks like" a class method.
1)
include
在类A
的实例上添加方法、常量和变量;extend
将这些内容添加到Class
实例A
的实例中(有效定义类方法)。include my_module
将允许这样做:A.new.foo
extend my_module
将允许这样做:A.foo
更一般地说,
include
仅在Class
或Module
上有意义,而extend
可用于向任何添加方法。代码>对象。
2) 实际上:当使用
include
时,foo
是A
的实例方法...当使用extend
时,foo
是一个类方法。1)
include
adds methods, constants, and variables on instances of classA
;extend
adds those things to the instance of theClass
instanceA
(effectively defining class methods).include my_module
will allow this:A.new.foo
extend my_module
will allow this:A.foo
More generally,
include
only makes sense on aClass
orModule
, whileextend
can be used to add methods to anyObject
.2) In effect: when using
include
,foo
is an instance method ofA
... when usingextend
,foo
is a class method.