Chapter 7

Objects and Classes

So far in this tutorial we’ve seen many examples of Ruby objects. In this chapter, we’ll learn how to use Ruby classes to make objects of our own, which have both attributes (data) and methods (functions) attached to them.

7.1 Defining Classes

As we saw in Section 4.2, Ruby objects can be created (or instantiated) using the class name and the new constructor method:

>> String.new("Madam, I'm Adam.")
=> "Madam, I'm Adam."
>> Time.new(1969, 7, 20, 20, 17, 40)
=> 1969-07-20 20:00:00 -0700

We can create a class of our own using three basic elements:

1. Use the class keyword to define the class.

2. Use the special initialize method to specify the behavior of new.

3. Use an attribute accessor ...

Get Learn Enough Ruby to Be Dangerous: Write Programs, Publish Gems, and Develop Sinatra Web Apps with Ruby 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.