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) 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) What is wrong with 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 same42
, but then the invariantobj.clone.object_id != obj.object_id
would no longer hold,42.clone
wouldn't actually be cloning.Fixnum is a special class given special treatment by the language. From the time your program launches, there is precisely one Fixnum for every number that the class can represent, and they're given a special representation that doesn't take any extra space — this way, basic math operations aren't allocating and deallocating memory like crazy. Because of this, there cannot be more than one 42.
For the others, they all have one thing in common: They're singletons. There's only one instance of a singleton class by definition, so trying to clone it is an error.
I did a
git grep "can't clone"
of YARV's source code, and gotThe first and third lines indicate you can't clone a singleton.
The second line refers to
rb_special_const_p(obj)
. But this is going beyond my ken.Rails appears to extend the classes you mention with a "duplicable?()" method.
http://api.rubyonrails.org/files/activesupport/lib/active_support/core_ext/object/duplicable_rb.html
I still don't know how to test for clonability properly but here's a very clunky, evil way to test for clonablity using error trapping:
And here's how you can clone even the unclonable. At least for the very few classes I've tired it with.
Here's some sample testing:
You can't clone immutable classes. I.e. you can have only one instance of object 42 (as a Fixnum), but can have many instances of "42" (because string is mutable). You can't clone symbols as well since they are something like immutable strings.
You can check that in IRB with object_id method. (symbols and fixnums will give you same object_id after repetitive calls)