简体   繁体   English

Ruby的Class方法的dup和clone方法

[英]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)

Notes 笔记

  • 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 . dupclone内部调用了initialize_copy ,因此这是查找类如何覆盖dupclone的起点。
  • Later versions of ruby added initialize_clone and initialize_dup to fine tune overrides of clone and dup . 红宝石的更高版本添加了initialize_cloneinitialize_dup来微调clonedup覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM