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

标签 ruby clone idioms dup

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/

相关文章:

haskell - 用于学习惯用 Haskell 的资源(eta 缩减、符号中缀运算符、库等)

html - 如何使用 nokogiri 去除 html 空格和评论以及 javascript 评论?

Ruby:将数组的所有元素相乘

git - GoDaddy 出站 SSH 与 Git 克隆问题

java - 克隆列表 - 它是如何完成的?

用于测试命令是否存在的 PowerShell 习语?

ruby - 更好的 ruby​​ 语法

java - Watir-webdriver 结合 java

python - 复制生成器

java - 我应该在 Java 中用什么替换小结构?