Ruby’s Built-In Classes: Class, Object, Module, and BasicObject

Ruby’s built-in classes have some paradoxical relationships that cannot be explained in Ruby and only work because the classes are assumed to exist. This post outlines important facts about the core classes that all Ruby programmers should know without going down the paradox rabbit hole.

1. All classes are instances of the Class class

Object.class # => Class
Module.class # => Class
class A; end
A.class # => Class
Fixnum.class # => Class

Creating classes with Class#new() isn’t very practical, but it illustrates how all user defined classes are instances of Class nicely.

Mammal =
Mammal.class # => Class
Dog = # Dog inherits from Mammal
Dog.class # => Class

2. Even the Class class is an instance of Class
All classes are instances of the Class class and Class is not an exception. It seems circular that Class is an instance of itself, but it’s true.

Class.class # => Class

Don’t worry too much about this paradox – just accept it.

3. Every Ruby class has one superclass, except BasicObject, which doesn’t have a superclass
Every Ruby class inherits from exactly one other class, except BasicObject.

class A; end
A.superclass # => Object
Object.superclass # => BasicObject

The ancestors() method is a convenient way to view the entire inheritance chain with the included modules.

class A; end
A.ancestors # => [A, Object, Kernel, BasicObject]

4. The Module class is used to instantiate new modules
The Module class is not a module – it’s a class that’s used to create modules. Modules and classes are very similar, except classes can be instantiated. There are two ways the Module class can be instantiated:

# one technique to create a module
module Abbot; end

# another technique to create a module
Redwall =

As Jorg Mittag points out, core classes don’t have to completely make sense in Ruby because they fall out of thin air and ‘are simply assumed to exist’. Jorg’s post lists several paradoxes that cannot be explained with Ruby. Make sure to learn the basics and don’t get too caught up in the details.

P.S. John’s StackOverflow answer is another great learning resource.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s