The Object#class() and Class#superclass() methods are often used to uncover paradoxes in the Ruby object model. These paradoxes cannot be explained in Ruby alone and only work because they’ve magically been set up to work by the language designer. This post first examines the Object#class() and Class#superclass() methods and then demonstrates some paradoxes.
1. The Object#class() method returns the class that instantiated the object.
All classes in Ruby are instances of the Class class.
Object.class # => Class class A; end A.class # => Class
The instantiating class varies for all objects in Ruby that are not class objects.
class A; end A.new.class # => A {}.class # => Hash 4.class # => Fixnum
2. The Class#superclass() method returns the parent class in the inheritance chain.
Every Ruby class has a single superclass except BasicObject, which is the end of the inheritance chain and doesn’t have a superclass. For example, the Hash class’s superclass (also referred to as the ‘parent class’) is Object because Hash inherits from Object.
Hash.ancestors # => [Hash, Enumerable, Object, Kernel, BasicObject] Hash.superclass # => Object
User defined classes inherit from Object by default
class A; end A.superclass # => Object
User defined classes can inherit from a class other than Object
class A; end class B < A; end B.superclass # => A
3. There are paradoxes in the Ruby object model that only work because of the way the language designer has set up the built-in classes. These paradoxes cannot be explained with Ruby per se and it’s best to get familiarized with the paradoxes without going too far down the rabbit hole.
Class is an instance of the Class class
Class.class # => Class
Class’s superclass is Module, but Module’s class is Class
Class.superclass # => Module Module.class # => Class
Jorg Mittag lists some other paradoxes in this StackOverflow post.
The Object#class() and Class#superclass() are often used to uncover the paradoxes in the Ruby object model. My recommendation is to understand the paradoxes that exist in the Ruby object model and then move on without spending too much time.