1. Computing
Send to a Friend via Email

Ruby's Class Hierarchy for Numbers


All numbers are represented by some descendant of the Numeric class. All of these classes know how to perform operations on each other, so there's no need to worry about what type these numbers are. For example, you can multiply a native integer with a floating point number (a number with a decimal point) or a Bignum without knowing which is the native integer and which is the Bignum. Ruby can also readily convert between these numbers, without the programmer or the user having known it was done.

Native integers are represented by the Fixnum class. It's called Fixnum because it has a fixed size. These are the native binary numbers discussed above. They're fast, the computer knows how to work with them and they're everything more people will ever need.

When an operation between two Fixnum objects creates an overflow (a result too big for the Fixnum to store), Ruby will automatically convert the numbers to a Bignums, perform the operation again and store the result in a Bignum. The Bignum is returned from the operator and stored in the variable just like a Fixnum would be. The programmer doesn't have to know the Bignum even exists.

Try this in your IRB console. Assign the number 12 to a variable. Continually multiply that variable by itself and check the type of the number with the class instance. Eventually, you'll see the number turn from a Fixnum into a Bignum, silently and transparently.

 irb(main):001:0> a = 12
 => 12
 irb(main):002:0> a *= a
 => 144
 irb(main):003:0> a.class
 => Fixnum
 irb(main):004:0> a *= a
 => 20736
 irb(main):005:0> a.class
 => Fixnum
 irb(main):006:0> a *= a
 => 429981696
 irb(main):007:0> a.class
 => Fixnum
 irb(main):008:0> a *= a
 => 184884258895036416
 irb(main):009:0> a.class
 => Bignum

©2014 About.com. All rights reserved.