Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book