Concepts of Programming Languages

(Sean Pound) #1
11.4 Language Examples 501

The alternative is to call the access control functions with the names of
the specific methods as parameters. For example, the following is semantically
equivalent to the previous class definition:


class MyClass
def meth1


...
end
...
def meth7
...
end
private :meth7,...
end # of class MyClass


In Ruby, all data members of a class are private, and that cannot be changed.
So, data members can be accessed only by the methods of the class, some of
which may be accessor methods. In Ruby, instance data that are accessible
through accessor methods are called attributes.
For an instance variable named @sum, the getter and setter methods would
be as follows:


def sum
@sum
end
def sum=(new_sum)
@sum = new_sum
end


Notice that getters are given the name of the instance variable minus the @. The
names of setter methods are the same as those of the corresponding getters,
except they have an equal sign (=) attached.
Getters and setters can be implicitly generated by the Ruby system by
including calls to attr_reader and attr_writer, respectively, in the class
definition. The parameters to these are the symbols of the attribute’s names,
as is illustrated in the following:


attr_reader :sum, :total
attr_writer :sum


11.4.6.3 An Example


Following is the stack example written in Ruby:


Stack.rb - defines and tests a stack of maximum length


100, implemented in an array

Free download pdf