rubyfixnum

Ruby max integer


I need to be able to determine a systems maximum integer in Ruby. Anybody know how, or if it's possible?


Solution

  • Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.

    If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:

    machine_bytes = ['foo'].pack('p').size
    machine_bits = machine_bytes * 8
    machine_max_signed = 2**(machine_bits-1) - 1
    machine_max_unsigned = 2**machine_bits - 1
    

    If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1 (or 2**62 - 1), because one bit is used to mark it as an integer instead of an object reference.