4.5. Objects and Classes

Ruby wouldn't be much of an object-oriented language if you weren't able to define your own classes and objects. The next few sections show you how.

4.5.1. Defining and Instantiating Classes

Classes are defined through the class keyword, followed by the capitalized name of the class. The name needs to be capitalized because, as mentioned before, classes in Ruby are constants:

class Account
end

As usual, the definition is terminated by end, and any line of code contained between class and end forms the body of the class. From the defined class you can obtain an object by invoking the new method:

account = Account.new
account.class                 # Account

By employing the Object#is_a? method, you can determine whether or not an object is an instance of a given class:

account.is_a? Account         # true

The same method can also be used to verify if a class is a superclass of the class of an instance (or an ancestor class in the inheritance hierarchy):

account.is_a? Object          # true

The preceding line tells you that Object is a superclass or an ancestor for the Account class. It's actually a superclass as you can see if you run the following:

account.class.superclass      # Object

You may notice that no method is specified in the Account class, but it was still possible to instantiate it thanks to the fact that the constant Account is a Class object, and as such, it has access to a new method for creating instances.

4.5.1.1. The initialize Method

An empty class defined in this manner ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.