哪些Ruby类支持.clone? [英] Which Ruby classes support .clone?
问题描述
Ruby在对象中定义了 #clone
。
让我惊讶的是,有些类在调用它时会引发异常。
我发现 NilClass , TrueClass , FalseClass , Fixnum 具有这种行为。
Ruby defines #clone
in Object.
To my suprise, some classes raise Exceptions when calling it.
I found NilClass, TrueClass, FalseClass, Fixnum having this behaviour.
1)是否存在完整的类列表(至少是核心类),不允许使用 #clone
?
还是有办法检测特定的类是否支持 #clone
?
1) Does a complete list of classes (at least core-classes) exist, which do not allow #clone
?
Or is there a way to detect if a specific class supports #clone
?
2)什么 42.clone
是错误的吗?
2) What is wrong with 42.clone
?
推荐答案
我不认为有一个正式的清单,至少除非您希望阅读其中的内容。 2)无效的原因是由于对Fixnums进行了优化。它们在内部存储/传递为其实际值(即true,false和nil),而不是作为指针。天真的解决方案是让 42.clone
返回相同的 42
,但是不变的 obj.clone.object_id!= obj.object_id
将不再成立, 42.clone
实际上不会被克隆。
I don't think there is a formal list, at least unless you count reading the source. The reason 2) doesn't work is because of an optimization applied to Fixnums. They are stored/passed internally as their actual values (so are true, false and nil), and not as pointers. The naive solution is to just have 42.clone
return the same 42
, but then the invariant obj.clone.object_id != obj.object_id
would no longer hold, 42.clone
wouldn't actually be cloning.
这篇关于哪些Ruby类支持.clone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!