71

I know that the Fixnum class inherits from the Integer class. But what is the actual difference between them? Are there any use cases where we sometimes use Fixnum, and sometimes use Integer instead?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

2 Answers2

86

UPDATE: As of Ruby 2.4, the Fixnum and Bignum classes are gone, there is only Integer. The exact same optimizations still exist, but they are treated as "proper" compiler optimizations, i.e. behind the scenes, invisible to the programmer.


This is somewhat confusing. Integer is the real class that you should think about. Fixnum is basically a performance optimization that should never have been made visible to the programmer in the first place. (Compare this with flonums in YARV, which are implemented entirely as an optimization inside the VM, and never exposed to the programmer.)

Basically, Fixnums are fast and Bignums are slow(er), and the implementation automatically switches back and forth between them. You never ask for one of those directly, you will just get one or the other, depending on whether your integer fits into the restricted size of a Fixnum or not.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 5
    So if you want to implement something like `3.to_roman`, you should extend `Integer` and not `Fixnum` right? – Dennis Jan 19 '15 at 22:31
  • 3
    Doing so would make `to_roman` available to both `Fixnum` and `Bignum`. If that's your goal, then yes. – Frank Koehl Apr 17 '15 at 14:14
  • It's not really clear whether you and @matt contradict each other about the pre-"Ruby 2.4" state of affairs. – x-yuri Oct 27 '21 at 19:49
45

You never "use" Integer. It is an abstract class whose job is to endow its children (Fixnum and Bignum) with methods. Under effectively no circumstances will you ever ask for an object's class and be told that it is an Integer.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 20
    This answer was correct for Ruby 2.3 and older versions. It is wrong as of Ruby 2.4. See the other [answer](https://stackoverflow.com/questions/21372649/what-is-the-difference-between-integer-and-fixnum/21411269#21411269). – Eric Duminil Jun 13 '17 at 21:25
  • 1
    @matt when you say "You never "use" `Integer`. It is an abstract class whose job is to endow its children (`Fixnum` and `Bignum`) with methods", is it the same as: `Integer` is an abstract class that defines the interface for its subclasses `Fixnum` and `Bignum` and you never instantiate using an abstract class? – nonopolarity Jul 08 '19 at 07:08