Numbers and Class Hierarchy in Ruby
In this article we’re going to explore the following topics:
- the
Numeric
subclasses; - the
Numeric
ancestor 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 the
Ruby Object Model
article if you are unfamiliar with theObject
class and the ancestor chain.Feel free to read the
Comparable module
article if you are unfamiliar with theComparable
module.
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚