Search code examples
rubyinternals

Size function for ruby Fixnum class


Why the ruby size function for the number returning output like this?

1000000.size              # => 8
99999999999999999999.size # => 9

Solution

  • Ruby internally uses two different structures for storing integers - Fixnum and Bignum. The first one is used for smaller number and maps directly to a long integer on the host architecture. It's faster and constant in size, but limited on how much it can store. The latter is used for storring arbitrarily large numbers and its size depends on how big the number is.

    1000000.class              # => Fixnum
    99999999999999999999.class # => Bignum
    

    The conversion is done internally. In fact with ruby 2.4.0, there will be only one class - Integer.