Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby
next up previous index

Attribute Accessors

Program gif continues the definition of the Complex class. It defines two attribute accessors   called real and image.

   program56255
Program: Complex class real and imag attribute accessors.

The effect of the statement ``attr_accessor :symbol'' is equivalent to the following:

def symbol
    @symbol
end

def symbol=(value)
    @real = symbol
end
That is, the declaration of an attribute accessor has the effect of creating a pair of methos--one method that returns the current value of the corresponding attribute, the other method assigns a new value to the corresponding attribute.

Thus, Program gif defines two methods real and real=, that access the instance attribute @real and two methods imag and image=, that access the instance attribute @imag.

A method that accesses an instance but does not modify that instance is called an attribute reader  . Therefore, real and imag are attribute readers.

The real= and imag= methods provide the means to modify the @real and @imag instance attributes, respectively. A method that modifies an instance attribute is called an attribute writer  . Therefore, real= and image= are attribute writers.

Ruby provides the means to declare attribute readers and writers separately. The sequence of declarations

attr_reader :real
attr_writer :real
is equivalent to the declaration
attr_accessor : real

The dot operator is used to specify the object on which an accessor method is to be invoked. For example, the statement

c.real = 2
invokes the attribute writer method real=. The effect of this is to make the @real instance attribute refer to a Fixnum object that has the value 2.

Program gif defines four more methods of the Complex class: r, r=, theta and theta=.

   program56299
Program: Complex class r, coder=, theta and theta= methods.

The r and theta methods are accessor  methods that return the polar coordinates of the given complex number. Similarly, the r= and theta= methods are mutatormutator methods that handle the assignment of polar coordinate values to the given complex number.


next up previous index

Bruno Copyright © 2004 by Bruno R. Preiss, P.Eng. All rights reserved.