Numbers and Class Hierarchy in Ruby

In this article we’re going to explore the following topics:
- the
Numericsubclasses; - the
Numericancestor chain.
The Numeric subclasses
The Numeric class is the highest class within the numeric classes family.
The following classes inherit directly from this class: Integer, Float, BigDecimal, Complex and Rational.
irb> require 'bigdecimal'
=> true
irb> Integer.superclass
=> Numeric
irb> Float.superclass
=> Numeric
irb> BigDecimal.superclass
=> Numeric
irb> Complex.superclass
=> Numeric
irb> Rational.superclass
=> Numeric
This class contains a common bunch of methods for:
- math operations
- rounding numbers
and a bunch of predicate methods as zero?, negative?, etc..
The definition of some operators —such as the / — are left to each subclass.
irb> 1.class
=> Integer
irb> Integer.superclass
=> Numeric
irb> Numeric.instance_methods(false).include?(:/)
=> false
irb> Integer.instance_methods(false).include?(:/)
=> true
Here, 1 is a single immutable object which is an instance of Integer.
We can see that the Numeric class doesn’t define any / instance method.
In contrary, the Integer class defines a / instance method.
The Numeric ancestor chain
As we can see, the Numeric class is a very important one, as it’s the common base of any numeric classes in Ruby.
So let’s break down its ancestor chain
irb> Numeric.ancestors
=> [Numeric, Comparable, Object, Kernel, BasicObject]
irb> Numeric.included_modules
=> [Comparable, Kernel]
The Numeric class inherit from the default Object class.
It also includes the Comparable module which is in charge of adding a bunch of comparison operators to a class.
This class shares the exact same ancestor chain as the String class.
Feel free to read theRuby Object Modelarticle if you are unfamiliar with theObjectclass and the ancestor chain.
Feel free to read theComparable modulearticle if you are unfamiliar with theComparablemodule.
Voilà !

Thank you for taking the time to read this post :-)
Feel free to 👏 and share this article if it has been useful for you.
You can follow me here. I publish an average of 2 articles per week.
My Ruby 💌 newsletter 💌 is available here ! Feel free to subscribe ! 🚀
Here is a link to my last article: The ENV Object.