I want to be able to assign a variable the number 2147483647, the maximum 32-bit signed integer value. Is there some way that I can retrieve a value from the class, such as Integer::MAX?
Asked
Active
Viewed 1,149 times
0
-
6This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). Why do you want to do this? What's the problem you're trying to solve? – Jordan Running Jun 06 '19 at 19:42
-
2There is no maximum integer in Ruby. – Jörg W Mittag Jun 06 '19 at 19:47
-
1`class Integer; MAX = 2147483647; end` if you need it in the base class, but [I don't recommend](https://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/) monkey patching base classes. Just put it in one of your own classes. – anothermh Jun 06 '19 at 20:10
-
You can easily calculate the value: `MAX_INT = (1 << 31) - 1` – Stefan Jun 07 '19 at 08:00
1 Answers
7
In CRuby 2.5 and newer you can do the following:
require 'rbconfig/sizeof'
RbConfig::LIMITS['INT32_MAX'] # => 2147483647
The keys of RbConfig::LIMITS
are the names of C limit macros (see <limits.h>
, <stdint.h>
and <float.h>
) except FIXNUM_*
which is a Ruby implementation detail.
I recommend defining your own constant (or local variable) for these limits though. It's more portable.

cremno
- 4,672
- 1
- 16
- 27