问题描述
一般来说,clone
和 dup
在后代类中可能有不同的语义.clone
用于复制对象,包括其内部状态,dup
通常使用后代对象的类来创建新实例.
但是当我做一些测试时,我发现它们实际上是一样的:
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 methodsis often my source for answers to these questions, since it is quite clear, and a fairly compliant Ruby implementation.
这篇关于Ruby 的 dup 和 clone 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!