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

前端之家收集整理的这篇文章主要介绍了何时使用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比克隆更多.到目前为止,我从来没有使用过克隆,直到明确需要我才会使用克隆.

原文链接:https://www.f2er.com/ruby/271448.html

猜你在找的Ruby相关文章