Defining a Simple Class

We begin our coverage of classes with an extended tutorial that develops a class named Point to represent a geometric point with X and Y coordinates. The subsections that follow demonstrate how to:

  • Define a new class

  • Create instances of that class

  • Write an initializer method for the class

  • Add attribute accessor methods to the class

  • Define operators for the class

  • Define an iterator method and make the class Enumerable

  • Override important Object methods such as to_s, ==, hash, and <=>

  • Define class methods, class variables, class instance variables, and constants

Creating the Class

Classes are created in Ruby with the class keyword:

class Point
end

Like most Ruby constructs, a class definition is delimited with an end. In addition to defining a new class, the class keyword creates a new constant to refer to the class. The class name and the constant name are the same, so all class names must begin with a capital letter.

Within the body of a class, but outside of any instance methods defined by the class, the self keyword refers to the class being defined.

Like most statements in Ruby, class is an expression. The value of a class expression is the value of the last expression within the class body. Typically, the last expression within a class is a def statement that defines a method. The value of a def statement is always nil.

Instantiating a Point

Even though we haven’t put anything in our Point class yet, we can still instantiate it:

p = Point.new

The constant Point holds ...

Get The Ruby Programming Language 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.