`
biyeah
  • 浏览: 203822 次
  • 来自: ...
社区版块
存档分类
最新评论

[转]Ruby - DUP vs CLONE

    博客分类:
  • Ruby
 
阅读更多
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
引用
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.
分享到:
评论

相关推荐

    Ruby-Ruby中的GoF设计模式实现

    Ruby支持对象的克隆,`Object#clone`或`Object#dup`方法可以实现原型模式。 6. **适配器模式**:将一个类的接口转换成客户希望的另一个接口。Ruby的鸭子类型特性使得适配器模式尤为自然,只需确保对象响应所需的...

    ruby api

    1. Object:所有Ruby对象的基类,包含了一些通用的方法,如`object_id`用于获取对象的唯一标识,`==`进行对象的比较,`clone`和`dup`用于创建对象的副本。 2. String:处理文本字符串的类,提供了丰富的字符串操作...

    ruby数组

    - **复制数组**:`clone`或`dup`可以创建数组的副本,避免原数组被修改。 ### 数组迭代 Ruby提供了许多迭代方法来处理数组中的每个元素,如`each`、`map`、`each_with_index`等。例如: ```ruby arr.each { |...

    ruby学习笔记

    `dup` 和 `clone` 都可以用来复制字符串,但它们之间存在细微的区别。 #### 5. 转换 - `capitalize`: 将字符串的第一个字符转换为大写,其余字符转换为小写。 - `upcase`: 将整个字符串转换为大写。 - `downcase`:...

    Ruby中Hash哈希结构的基本操作方法小结

    要避免这种情况,可以使用`clone`或`dup`方法创建副本: ```ruby h3 = h2 # 浅复制,改变h3会影响h2 h4 = h2.clone # 深复制,改变h4不会影响h2 ``` 至于Hash的排序,由于键和值可能为任意类型,排序并不直接。Ruby...

    value_struct:Ruby 中的只读结构

    strict_arguments值结构需要使用确切数量的参数进行初始化:freeze自动冻结新实例:no_clone更改#clone以返回相同的对象默认情况下,只包含:dup_with_changes 。 没有 mixins,ValueStructs 几乎和普通结构一样快。 ...

    简要说明Ruby中的迭代器

    需要注意的是,如果只是想复制一个数组而不进行任何转换,应该使用`clone`或`dup`方法,而不是`collect`。`collect`更适用于对每个元素进行某种计算或转换,以生成一个新的、有变化的数组。 总结来说,Ruby中的迭代...

    ExoRubyPOO

    7. 原型(Prototype)继承:虽然 Ruby 使用类来表示继承关系,但它的原型概念体现在 `Object#clone` 和 `Object#dup` 方法上,它们可以创建对象的副本。 8. 块(Blocks)和迭代器:Ruby 中的块是一段代码,可以用 `...

Global site tag (gtag.js) - Google Analytics