gpt4 book ai didi

ruby - 在 Ruby 中什么时候使用 dup,什么时候使用 clone?

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:29 26 4
gpt4 key购买 nike

What's the difference between Ruby's dup and clone methods?描述了 dupclone 的行为差异。但是什么时候应该使用dup,什么时候应该使用clone呢?

来自实际项目的例子讨论了为什么他们使用 dup 而不是 clone,反之亦然,这将是这个问题的理想选择。

或者,解释为什么存在这两种不同的方法会有所帮助。这可以引用 Ruby 的创建者的声明,或者对影响 Ruby 的语言中的 dupclone 方法的检查。

最佳答案

clone 确实复制了一个对象的frozen 状态,而dup 没有:

o = Object.new
o.freeze

o.clone.frozen?
#=> true

o.dup.frozen?
#=> false

clone 也会复制对象的单例方法,而 dup 不会:

o = Object.new
def o.foo
42
end

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

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

这让我假设 clone 有时被理解为提供比 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 一词再次用来指代深度克隆。据我所知,社区似乎没有达成共识,除了在需要特定副作用的情况下应该使用 clonedup任一个。

最后,我在 Ruby 代码中看到 dupclone 更频繁。到目前为止,我从未使用过 clone,除非我明确需要,否则我不会。

关于ruby - 在 Ruby 中什么时候使用 dup,什么时候使用 clone?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com