Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 134 ยท Object-Oriented Ruby

The Ruby Object Model

Understand how Ruby really works - classes are objects, how method lookup walks the ancestors chain, how constants are found, and what Class, Module and BasicObject are.

Up to now you have used classes, modules, inheritance and singleton methods as separate features. The object model is the small set of rules that ties them together. Once you know those rules, much of Ruby that looks like magic (why super works through a module, why Dog.new is just a method call, why a missing constant says uninitialized constant) turns into ordinary bookkeeping you can predict.

There are really only four ideas: everything is an object, every object has a class, classes are themselves objects, and every method call is resolved by walking one ordered list of modules and classes called the ancestors chain. This lesson builds each idea with code you can run. It builds on Classes and Objects, Inheritance, Modules and Mixins and Singleton Methods and the Singleton Class.

Classes are objects

In many languages a class is a compile-time blueprint. In Ruby a class is a living object that you can store in a variable, pass to a method, ask questions, and change while the program runs. Dog is a constant that refers to an object whose own class is Class.

Ruby A class is an instance of Class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Read the output as a map. Dog.class is Class, and Dog's parent chain is Object and then BasicObject, where it stops (the superclass of BasicObject is nil). Class itself inherits from Module, which inherits from Object. So a class is a kind of module with the extra ability to create instances. Class.class is Class: the loop closes, the way a dictionary defines the word "dictionary".

Class.new(StandardError) builds an anonymous class. Its name is nil until you assign it to a constant, at which point Ruby gives it the name of the first constant that refers to it. That is all the class Dog keyword does: create a Class object and assign it to the constant Dog.

There is no separate "type system" to learn. 5, "hi", nil, Dog and Dog.new are all objects, they all answer class, and they all respond to the same kind of method call.

Method calls and the ancestors chain

When you write obj.move, Ruby does not look in one place. It asks the object's class for the ancestors list and searches it from first to last until a class or module defines move. The first match wins, and super simply continues the search from the next entry.

Ruby Ancestors show the exact search order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

For Dog the order is Loud, Dog, Animal, Walk, Object, Kernel, BasicObject. Three rules produce this list:

  • A class comes first, then its superclass, and so on up to BasicObject.
  • A module added with include is inserted just after the class that included it. That is why Walk sits behind Animal.
  • A module added with prepend is inserted just before the class. That is why Loud comes before Dog.

Kernel is a module that Object includes. It holds puts, p, raise, require and the other "global" functions: they are really ordinary instance methods that every object inherits.

Watching lookup and super

Each super call moves one step down the chain. Here every entry defines move and calls super, so the output spells out the chain in order.

Ruby Following the chain with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line reads LOUD dog animal walking: Loud#move ran first, its super reached Dog#move, then Animal#move, and finally Walk#move, which does not call super, so the chain ends. Method#owner and super_method expose the same walk programmatically.

A singleton method like def d.move lives on a hidden class that Ruby puts at the very front of that one object's chain (see Singleton Methods and the Singleton Class). That is why d.move now starts with singleton and still reaches everything behind it through super.

When lookup fails

If the whole chain is searched without a hit, Ruby calls method_missing (see method_missing and respond_to_missing?). The default method_missing raises NoMethodError, and the message tells you what kind of receiver was involved.

Ruby NoMethodError tells you where the search ended

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The three messages are undefined method 'meow' for an instance of Dog, undefined method 'bark' for class Dog and undefined method 'upcase' for nil. The second one is a good reminder of the model: bark is an instance method, so it is stored in Dog's method table and is only found by instances. The class object Dog is an instance of Class, so its own chain is different and does not contain bark.

Where do class methods live?

A class method such as Dog.create cannot be stored in Dog's own method table (that table is for instances). Ruby gives every class a hidden singleton class (also called a metaclass or eigenclass) that holds the methods for the class object itself. You can see it with singleton_class.

Ruby Class methods live in the singleton class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Dog.singleton_class prints as #<Class:Dog>. Its superclass is #<Class:Object>, the singleton class of Object, and Puppy's singleton class inherits from Dog's. This parallel hierarchy is the reason class methods are inherited: Puppy.kind works because #<Class:Puppy> inherits from #<Class:Dog>, which defines kind.

And where does new come from? Class.instance_method(:new).owner prints Class: new is an ordinary instance method of Class. Since Dog is an instance of Class, Dog.new is a plain method call that allocates an object and then runs initialize. Nothing is built into the syntax.

Methods are looked up along the ancestors of the receiver. Constants are looked up differently, in two steps: first the lexical scopes you are physically written inside (the nesting), then the ancestors of the innermost class or module.

Ruby Lexical scope decides which X you get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Outer::Inner#show is written inside module Outer, so the lexical scope contains Outer, and it finds "outer". Outer::Flat was opened with the compact form class Outer::Flat, which does not put Outer into the nesting, so the search skips Outer, falls to the top level and finds "top". Module.nesting shows the nesting directly: [Outer] inside the module and [Outer::Inner, Outer] inside the class.

This is the practical reason many style guides prefer the nested form when your class needs sibling constants. A missing constant raises NameError:

Ruby NameError for constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The messages are uninitialized constant Missing and uninitialized constant Outer::Nope.

BasicObject: the root

At the top of every class chain is BasicObject. It is deliberately almost empty, which makes it the right parent for proxies and DSL objects that should not accidentally inherit methods like puts or class.

Ruby What BasicObject has

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

BasicObject has only eight instance methods (!, !=, ==, __id__, __send__, equal?, instance_eval, instance_exec). Everything else, including class, comes from Kernel via Object. Because Blank skips Object, b.class fails. Remember, too, that inside a BasicObject subclass even constants like String are not found, because constant lookup falls back to Object; write ::String there.

Why this matters in practice

Knowing the model changes how you debug and design:

  • Surprising behavior: call obj.method(:name).owner or Klass.ancestors to see which definition wins instead of guessing.
  • Mixins: include for adding behavior behind the class, prepend for wrapping it (a clean alternative to monkey patching, see Monkey Patching and Safe Alternatives).
  • Class-level state: class methods and class instance variables live on the class object and its singleton class, not on instances (Instance and Class Methods).
  • Metaprogramming: define_method, send and hooks all work by adding to or searching these same tables (Introduction to Metaprogramming).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the class of the object that the constant Dog refers to (after class Dog; end)?

    Dog is a class, and every class is an instance of Class. Dog.class returns Class.
  2. 2. For class Dog < Animal; prepend Loud; end, where does Loud appear in Dog.ancestors?

    prepend inserts the module in front of the class, so its methods are found first. include would put it right after the class.
  3. 3. Why does Puppy.kind work when kind is defined with def self.kind in the parent class Dog?

    Singleton classes form a hierarchy parallel to the normal one, so class methods are found through inheritance.
  4. 4. In class Outer::Flat; def show = X; end, why might X not be found inside Outer?

    Constant lookup checks the lexical nesting first. Writing class Outer::Flat leaves Outer out of Module.nesting, so Outer's constants are skipped.
  5. 5. What is Class.instance_method(:new).owner, and what does it tell you?

    new is an ordinary method defined in Class. Dog.new works because Dog is an instance of Class.

Summary

  • Everything is an object, and classes and modules are objects too: Dog.class is Class, Class inherits from Module.
  • Method calls walk ancestors from first to last; include inserts a module after its class, prepend before it, and super continues from the next entry.
  • Class methods live in a class's singleton class, and singleton classes inherit in parallel to classes, so class methods are inherited.
  • new is a plain instance method of Class; Kernel supplies puts, raise and friends through Object.
  • Constants are searched lexically first (Module.nesting), then through the ancestors.
  • BasicObject is the nearly empty root; method(:x).owner and ancestors are the debugging tools for "which method ran?".

Next: Operator Overloading