Ruby 的 dup 和 clone 方法有什么区别? [英] What's the difference between Ruby's dup and clone methods?

查看:38
本文介绍了Ruby 的 dup 和 clone 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dup 的 Ruby 文档 说:

一般来说,clonedup 在后代类中可能有不同的语义.clone 用于复制对象,包括其内部状态,dup 通常使用后代对象的类来创建新实例.

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.

但是当我做一些测试时,我发现它们实际上是一样的:

But when I do some test I found they are actually the same:

class Test
   attr_accessor :x
end

x = Test.new
x.x = 7
y = x.dup
z = x.clone
y.x => 7
z.x => 7

那么这两种方法有什么区别?

So what are the differences between the two methods?

推荐答案

子类可以覆盖这些方法以提供不同的语义.Object 本身有两个关键区别.

Subclasses may override these methods to provide different semantics. In Object itself, there are two key differences.

首先,clone 复制单例类,而 dup 不会.

First, clone copies the singleton class, while dup does not.

o = Object.new
def o.foo
  42
end

o.dup.foo   # raises NoMethodError
o.clone.foo # returns 42

其次,clone 保留了冻结状态,而 dup 没有.

Second, clone preserves the frozen state, while dup does not.

class Foo
  attr_accessor :bar
end
o = Foo.new
o.freeze

o.dup.bar = 10   # succeeds
o.clone.bar = 10 # raises RuntimeError

这些方法的 Rubinius 实现通常是我回答这些问题的来源,因为它非常清晰,并且是一个相当合规的 Ruby 实现.

The Rubinius implementation for these methods is often my source for answers to these questions, since it is quite clear, and a fairly compliant Ruby implementation.

这篇关于Ruby 的 dup 和 clone 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆