From: Charles Oliver Nutter Date: 2009-09-04T00:54:08+09:00 Subject: Re: doubling numbers with Object#object_id On Wed, Aug 26, 2009 at 5:21 PM, Shot (Piotr Szotkowski) wrote: > EbFFA: > >> I was playing with Ruby and wrote an interesting method: > >>     def double n >>       n.object_id - 1 >>     end > >> Anyone know why this works? Why Ruby was implemented this way? > > Note that other Ruby implementations (JRuby, Rubinius, IronRuby…) do > not have to keep this contract; it’s best considered as MRI peculiarity. > But yes, I do find this design beautiful – as well as Ruby’s method > lookup: http://www.viddler.com/explore/CobyR/videos/1/ I don't know that it's particularly beautiful; it's just a side effect of Fixnums not having any internal state and not actually being objects in MRI. Because they are "immediates" they don't actually have an object_id. As a result, their object_id is just based on their actual value, 2n+1. All other objects then get stuffed into the remaining even object_ids, and fixnum.object_id - 1 == fixnum * 2. - Charlie