O'Reilly logo

The Ruby Programming Language by David Flanagan, 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

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 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