何时使用dup,何时在Ruby中使用clone?

What’s the difference between Ruby’s dup and clone methods?描述了dup和clone的行为差异.但是什么时候应该使用dup,何时应该使用clone?

讨论为什么使用dup而不是克隆的实际项目的例子,反之亦然,对于这个问题来说是理想的.

或者,解释为什么存在两种不同的方法将是有帮助的.这可以引用Ruby的创建者的声明,或者是在影响Ruby的语言中检查诸如dup和clone之类的方法.

解决方法

这是真的,克隆复制对象的冻结状态,而dup不:
o = Object.new
o.freeze

o.clone.frozen?
#=> true

o.dup.frozen?
#=> false

克隆还将复制对象的单例方法,而dup不会:

o = Object.new
def o.foo
  42
end

o.clone.respond_to?(:foo)
#=> true

o.dup.respond_to?(:foo)
#=> false

这导致我认为克隆有时被理解为提供比dup更“复杂”的假设.这里有一些关于这个主题的引语:

Comment on ActiveRecord::Base#initialize_dup from Rails 3

Duped objects have no id assigned and are treated as new records. Note
that this is a “shallow” copy as it copies the object’s attributes
only,not its associations. The extent of a “deep” copy is application
specific and is therefore left to the application to implement according
to its need.

An article about deep copies in Ruby

There is another method worth mentioning,clone. The clone method does the same thing as dup with one important distinction: it’s expected that objects will override this method with one that can do deep copies.

But then again,theres deep_dup in Rails 4

Returns a deep copy of object if it’s duplicable. If it’s not duplicable,returns self.

and also ActiveRecord::Core#dup and #clone in Rails 4

clone — Identical to Ruby’s clone method. This is a “shallow” copy. Be warned that your attributes are not copied. […] If you need a copy of your attributes hash,please use the #dup method.

这意味着在这里,dup这个词再次被用来指代一个深的克隆.据我所知,在社区中似乎没有共识,只要您需要使用clone和dup,当您需要任何一个特定的副作用时.

最后,我在Ruby代码中看到dup比克隆更多.到目前为止,我从来没有使用过克隆,直到明确需要我才会使用克隆.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...