8

What is the Ruby equivalent for Java's Integer.MAX_VALUE?. Hopefully native.

Runner Up: If no equivalent, I need to set this for a Time object, so instead of hardcoding the maximum date for an integer 2116-02-20, is there a system constant that would work for this?

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
user8897013
  • 443
  • 4
  • 15

1 Answers1

12

There's no maximum any more for integers, they automatically shift to "bignum" representation:

1 << 64
# => 18446744073709551616
(1 << 64) + 1
# => 18446744073709551617

There's really no limit other than memory:

1 << (1 << 16)
# => 20035299304...(thousands of digits)...05719156736

As for Time, it's similarly unbounded so now you can express times well after the heat death of the universe if you really want to:

Time.at(1<<128)
# => 10783118943836478994022445751222-08-06 04:04:16 -0400

This used to be limited to the usual +/- 2.1 billion range, subject to the 2038 problem but that hasn't been the case since Ruby ~1.9. I'm not sure where 2116 factors in except from a Windows perspective.

If you want to know the max/min that can be represented in a "native" integer then that's platform dependent. 32-bit and 64-bit binaries will have different limits.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • @StefanPochmann Ah, so it's just coincidental it uses the same system as Windows. – tadman Dec 19 '17 at 19:47
  • Thanks! Before I mark this as answered, can you clear two questions up below: So if I wanted to minimize BigNum usage, and keep my times in int, I have to keep them before 2116, 02, 20 correct? Question 1. Not sure if this includes the daytime hours on the 20th of February, 2116 or not (is 11:59:59 on February 19th the limit). Question 2. Also, can I tell if time is using an int or BigNum? .class returns Time, and .to_i seems to work on times greater then the above limit. – user8897013 Dec 19 '17 at 19:52
  • 4
    `Integer` used to be either a `Fixnum` or a `Bignum`; since Ruby 2.4 it's just `Integer`. – steenslag Dec 19 '17 at 20:57
  • 5
    I'm not sure what the concern is here. Why would you have trouble keeping times below that value? This sounds like a data validation problem more than a Ruby implementation one. Unless you're dealing with millions of time objects per second the overhead of bignum is really hard to measure. You're more likely going to have problems serializing these to a database. For example, MySQL supports the range 1000CE through 9999CE. Postgres is different, it's 4713BCE to 5874897CE. You'll need to clamp to the weakest link in the chain which, given Ruby's implementation, is not Ruby. – tadman Dec 19 '17 at 22:13