加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:35:48 所属栏目:百科 来源:网络整理
导读:What’s the difference between Ruby’s dup and clone methods?描述了dup和clone的行为差异.但是什么时候应该使用dup,何时应该使用clone? 讨论为什么使用dup而不是克隆的实际项目的例子,反之亦然,对于这个问题来说是理想的. 或者,解释为什么存在两种不同
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比克隆更多.到目前为止,我从来没有使用过克隆,直到明确需要我才会使用克隆.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读