Ruby - Class Accessor Methods

Introduction

Consider the following code:


class Thing       
   def initialize( aName, aDescription ) 
     @name         = aName 
     @description  = aDescription 
   end 
                          
  def get_name 
      return @name 
  end 
                           
  def set_name( aName ) 
      @name = aName 
  end 
                           
  def get_description 
      return @description 
  end 
                           
  def set_description( aDescription ) 
      @description = aDescription  
  end 

end  

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 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 do this, to modify the Product class definition.

One way of accomplishing this would be to rewrite the accessor methods for @description as follows:

def description 
    return @description 
end 
                           
def description=( aDescription ) 
    @description = aDescription 
end 

We have added accessors. Here, the get accessor is called description, and the set accessor is called description=.

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 = "new value" 

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 ) 

Related Topic