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

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

问题描述

用于 Ruby文档dup 说:


通常,克隆 dup 在后代类中可能具有不同的语义。 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.

首先,克隆复制单例类,而 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

第二,克隆保存冻结的状态,而 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天全站免登陆