Accessor Methods

Although the classes in this would-be adventure game work well enough, they are still fairly verbose because of all those get and set accessors. Let’s see what you can do to remedy this.

Instead of accessing the value of the @description instance variable with two different methods, get_description and set_description, like this:

puts( t1.get_description )
t1.set_description("Some description" )

it would be so much nicer to retrieve and assign values just as you would retrieve and assign values to and from a simple variable, like this:

puts( t1.description )
t1.description = "Some description"

To be able to do this, you need to modify the Treasure class definition. One way of accomplishing this would be to rewrite the accessor methods for @description as follows:

accessors1.rb

def description
    return @description
end

def description=( aDescription )
    @description = aDescription
end

I have added accessors similar to these in the accessors1.rb program. Here, the get accessor is called description, and the set accessor is called description= (that is, it appends an equals sign to the method name used by the corresponding get accessor). It is now possible to assign a new string like this:

t.description = "a bit faded and worn around the edges"

And you can retrieve the value like this:

puts( t.description )

Note that when you write a set accessor in this way, you must append the = character to the method name, not merely place it somewhere between the method name and the arguments. In other words, this is correct:

def name=( aName )

but this results in an error:

def name   =  ( aName )
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.227.82