Chapter 3

Objects, Classes and Modules

image
I always think about object oriented
programming in the supermarket.

We all learn very early on that Ruby is an object oriented language, descended from languages like Smalltalk and Simula. Everything is an object and all Ruby programs consist of a set of objects and the messages that are sent back and forth among them. Typically, we learn about object oriented programming by looking at how to use objects and what they can do: how they can group together data values and behavior related to those values, how each class should have a single responsibility or purpose or how different classes can be related to each other through encapsulation or inheritance.

But what are Ruby objects, exactly? What information does an object contain? If I were to look at a Ruby object through a microscope, what would I see? Are there any moving parts inside? And what about Ruby classes? All of us know how to create and use Ruby classes, but what exactly is a class? Finally, what are modules in Ruby? How are modules and classes related? What happens when I include a module into a class? How does Ruby determine which class or module implements a given method?

In this chapter I am going to answer these questions by exploring how Ruby works internally. Looking at exactly how Ruby implements objects, classes and modules can give you some insight into how they were intended to be used, and into how to write object oriented programs using Ruby.

Chapter 3 Roadmap

  1. What's inside a Ruby object?
    1. Generic objects
    2. Do generic objects have instance variables?
  2. Experiment 3-1: How long does it take to save a new instance variable?
  3. Deducing what's inside the RClass structure
    1. The actual RClass structure
  4. Experiment 3-2: Where does Ruby save class methods?
  5. How Ruby implements modules and method lookup
    1. What happens when you include a module in a class?
    2. Ruby's method lookup algorithm
    3. Including two modules in one class
  6. Experiment 3-3: Modifying a module after including it
  7. Objects, classes and modules in JRuby
  8. Objects, classes and modules in Rubinius