[转]Ruby - DUP vs CLONE

本文深入探讨了Ruby中DUP和CLONE的使用方式,它们都用于创建对象的浅拷贝,但具体操作和效果存在细微差别。文章通过实例展示了在不同场景下如何选择使用DUP或CLONE,特别强调了CLONE在复制对象状态上的优势,以及DUP在特定情况下的局限性。最后,作者分享了一个实际案例,说明在使用DUP复制ActiveRecord对象时可能会遇到的问题,以及使用CLONE解决这一问题的方法。
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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值