Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Ruby classes support .clone?

Tags:

clone

ruby

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 ?

like image 358
Julius Eckert Avatar asked Sep 13 '09 18:09

Julius Eckert


1 Answers

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.

like image 88
Logan Capaldo Avatar answered Sep 20 '22 22:09

Logan Capaldo