From: Stefano Crocco Date: 2009-12-22T22:23:48+09:00 Subject: Re: integers and floats On Tuesday 22 December 2009, Rajinder Yadav wrote: > |Can someone explain to me why Ruby treats integers and floating point > |numbers differently? > | > |irb(main):069:0> 12.equal? 12 > |=> true > | > |irb(main):071:0> 12.0.equal? 12.0 > |=> false equal? returns true if two objects are the same, that is if they have the same object_id. Integers represented by the Fixnum class are created only once: if I write x = 123456 y = 123465 ruby will create an instance of class Fixnum representing the number 123456 in the first line, but in the second line it doesn't create a new one and simply uses the one which already exists. This is the same thing which happens for symbols. On the other hand, the same doesn't happen for objects of class Float: here a different instance is created every time: x = 123.456 y = 123.456 produces two different objects representing the same floating point number. You can check this looking at the object_id of the different objects. I hope this helps Stefano