Chapter 7. Classes and Modules

image with no caption

Ruby is an object-oriented language in a very pure sense: every value in Ruby is (or at least behaves like) an object. Every object is an instance of a class. A class defines a set of methods that an object responds to. Classes may extend or subclass other classes, and inherit or override the methods of their superclass. Classes can also include—or inherit methods from—modules.

Ruby’s objects are strictly encapsulated: their state can be accessed only through the methods they define. The instance variables manipulated by those methods cannot be directly accessed from outside of the object. It is possible to define getter and setter accessor methods that appear to access object state directly. These pairs of accessor methods are known as attributes and are distinct from instance variables. The methods defined by a class may have “public,” “protected,” or “private” visibility, which affects how and where they may be invoked.

In contrast to the strict encapsulation of object state, Ruby’s classes are very open. Any Ruby program can add methods to existing classes, and it is even possible to add “singleton methods” to individual objects.

Much of Ruby’s OO architecture is part of the core language. Other parts, such as the creation of attributes and the declaration of method visibility, are done with methods rather than true language keywords. This chapter begins with an extended tutorial that demonstrates how to define a class and add methods to it. This tutorial is followed by sections on more advanced topics, including:

  • Method visibility

  • Subclassing and inheritance

  • Object creation and initialization

  • Modules, both as namespaces and as includable “mixins”

  • Singleton methods and the eigenclass

  • The method name resolution algorithm

  • The constant name resolution algorithm

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.107.210