tags:

views:

209

answers:

3

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) Wtf? What is wrong with 42.clone ?

A: 

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)

Eimantas
Mutability has nothing to do with it (in fact, you can add state to a Fixnum).
Chuck
+3  A: 

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.

Logan Capaldo
+1  A: 

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.

Chuck