|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Ruby |
Program
continues the definition of the Complex class.
It defines two
attribute accessors
called real and image.

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
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 :realis 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 = 2invokes 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
defines four more methods of the Complex class:
r, r=, theta and theta=.

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.