http://railsblogger.blogspot.com/2009/03/ruby-dup-vs-clone.html
Ruby - DUP vs CLONE
Both DUP & CLONE can be used to create shallow copy of an object. Both copies the instance variables of obj. But we need to be selective in their usage.
Few difference between these are
1) CLONE copies both FROZEN and TAINTED state of an object, where as DUP only copies TAINTED state of an object.
2) With CLONE you can copy any singleton methods of an object but DUP does not support this.
CLONE is used to duplicate an object, including its internal state, DUP typically uses the class of the descendent object to create the new instance.
I had some bitter experience while using DUP for duplicating an ActiveRecord row, this ended up in losing the original one the same worked fine with CLONE.
A good article on Objects states can be found here
[quote]obj.dup → anObject
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.[/quote]
Ruby - DUP vs CLONE
Both DUP & CLONE can be used to create shallow copy of an object. Both copies the instance variables of obj. But we need to be selective in their usage.
Few difference between these are
1) CLONE copies both FROZEN and TAINTED state of an object, where as DUP only copies TAINTED state of an object.
2) With CLONE you can copy any singleton methods of an object but DUP does not support this.
CLONE is used to duplicate an object, including its internal state, DUP typically uses the class of the descendent object to create the new instance.
I had some bitter experience while using DUP for duplicating an ActiveRecord row, this ended up in losing the original one the same worked fine with CLONE.
A good article on Objects states can be found here
[quote]obj.dup → anObject
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.[/quote]
本文深入探讨了Ruby中DUP和CLONE的使用方式,它们都用于创建对象的浅拷贝,但具体操作和效果存在细微差别。文章通过实例展示了在不同场景下如何选择使用DUP或CLONE,特别强调了CLONE在复制对象状态上的优势,以及DUP在特定情况下的局限性。最后,作者分享了一个实际案例,说明在使用DUP复制ActiveRecord对象时可能会遇到的问题,以及使用CLONE解决这一问题的方法。
416

被折叠的 条评论
为什么被折叠?



