O'Reilly logo

Ruby in a Nutshell by Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Object-Oriented Programming

Phew, seems like a long time since I introduced Ruby as "the object-oriented scripting language," eh? But now you have everything you need to get the nitty-gritty details on how Ruby treats classes and objects. After you've mastered a few concepts and Ruby's syntax for dealing with objects, you may never want to go back to your old languages, so beware!

Classes and Instances

All Ruby data consists of objects that are instances of some class. Even a class itself is an object that is an instance of the Class class. As a general rule, new instances are created using the new method of a class, but there are some exceptions (such as the Fixnum class).

a = Array::new
s = String::new
o = Object::new

Methods

Class methods are defined with the def statement. The def statement adds a method to the innermost class or module definition surrounding the def statement. A def statement outside a class or module definition (at the top level) adds a method to the Object class itself, thus defining a method that can be referenced anywhere in the program.

When a method is called, Ruby searches for it in a number of places in the following order:

  1. Among the methods defined in that object (i.e., singleton methods).

  2. Among the methods defined by that object's class.

  3. Among the methods of the modules included by that class.

  4. Among the methods of the superclass.

  5. Among the methods of the modules included by that superclass.

  6. Repeats Steps 4 and 5 until the top-level object is reached.

Singleton ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required