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

问题描述

用于的说:

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

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


通常是我对这些问题的答案,因为它很清楚,并且相当合规的Ruby实现。

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

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

06-27 23:21