Ruby includes five built-in classes for representing numbers, and the standard library includes three more numeric classes that are sometimes useful. Figure 3-1 shows the class hierarchy.

Numeric class hierarchy

Figure 3-1. Numeric class hierarchy

All number objects in Ruby are instances of Numeric. All integers are instances of Integer. If an integer value fits within 31 bits (on most implementations), it is an instance of Fixnum. Otherwise, it is a Bignum. Bignum objects represent integers of arbitrary size, and if the result of an operation on Fixnum operands is too big to fit in a Fixnum, that result is transparently converted to a Bignum. Similarly, if the result of an operation on Bignum objects falls within the range of Fixnum, then the result is a Fixnum. Real numbers are approximated in Ruby with the Float class, which uses the native floating-point representation of the platform.

The Complex class represents complex numbers, of course. BigDecimal represents real numbers with arbitrary precision, using a decimal representation rather than a binary representation. And Rational represents rational numbers: one integer divided by another. In Ruby 1.8 these classes are in the standard library. In Ruby 1.9, Complex and Rational are built-in.

All numeric objects are immutable; there are no methods that allow you to change the value held by the object. If you pass a reference to a numeric object to ...

Get The Ruby Programming Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.