Concepts of Programming Languages

(Sean Pound) #1

564 Chapter 12 Support for Object-Oriented Programming


def initialize
@one = 1
@two = 2
end

# A getter for @one
def one
@one
end

# A setter for @one

def one=(my_one)
@one = my_one
end

end # of class MyClass

The equal sign (=) attached to the name of the setter method means that its
variable is assignable. So, all setter methods have equal signs attached to their
names. The body of the one getter method illustrates the Ruby design of
methods returning the value of the last expression evaluated when there is no
return statement. In this case, the value of @one is returned.
Because getter and setter methods are so frequently needed, Ruby provides
shortcuts for both. If one wants a class to have getter methods for the two
instance variables, @one and @two, those getters can be specified with the
single statement in the class:

attr_reader :one, :two

attr_reader is actually a function call, using :one and :two as the actual
parameters. Preceding a variable with a colon (:) causes the variable name to
be used, rather than dereferencing it to the object to which it refers.
The function that similarly creates setters is called attr_writer. This
function has the same parameter profile as attr_reader.
The functions for creating getter and setter methods are so named because
they provide the protocol for objects of the class, which then are called attri-
butes. So, the attributes of a class define the data interface (the data made
public through accessor methods) to objects of the class.
Ruby objects are created with new, which implicitly calls a constructor.
The usual constructor in a Ruby class is named initialize. A constructor in
a subclass can initialize the data members of the parent class that have setters
defined. This is done by calling super with the initial values as actual param-
eters. super calls the method in the parent class that has the same name as the
method in which the call to super appears.
Free download pdf