[英]Ruby's dup and clone method for Class methods
I have read a couple of questions about Ruby dup and clone method Ruby dup and clone . 我已经阅读了有关Ruby dup和clone方法Ruby dup和clone的几个问题。 I understand that
dup
doesn't copy the singleton
methods and clone does for any object. 我知道
dup
不会复制singleton
方法,而clone会复制任何对象。
I am trying to check wrt class methods but found it bit confusing:- 我正在尝试检查wrt类方法,但发现它有点令人困惑:-
class User
def self.active
'all active users'
end
end
DupUser = User.dup
DupUser.active #=> all active users'
CloneUser = User.clone
CloneUser.active #=> all active users'
As far as I know, class methods are just singleton methods too, then why does User.dup
copied the active
method ie actually a singleton method of User
. 据我所知,类方法也只是单例方法,那么
User.dup
为什么User.dup
复制active
方法,即实际上是User
的单例方法。
By design , singleton methods are retained when dup
is called on a Class or Module, which is what you're doing in your example. 根据设计 ,在类或模块上调用
dup
时, 将保留单例方法,这就是您在示例中所做的事情。 When you dup
an instance, singleton methods are not retained: dup
实例时,不会保留单例方法:
user = User.new
# This is a singleton method on an Object
def user.active
'all active users'
end
cloned_user = user.clone
cloned_user.active # => 'all active users'
duped_user = user.dup
duped_user.active # => undefined method `active' for #<User:0x00007fee1f89ae30> (NoMethodError)
def object.method
behaves the same as object.extend(module)
. def object.method
行为与object.extend(module)
相同。 Methods from module
are not dup
ed (with the same caveat for calling dup
on Classes or Modules). module
方法进行dup
(在类或模块上调用dup
时要注意相同的事项)。 dup
and clone
internally call initialize_copy
, so that's a starting point for finding how a Class overrides dup
or clone
. dup
和clone
内部调用了initialize_copy
,因此这是查找类如何覆盖dup
或clone
的起点。 initialize_clone
and initialize_dup
to fine tune overrides of clone
and dup
. initialize_clone
和initialize_dup
来微调clone
和dup
覆盖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.