Ruby - Using Attribute readers and writers


Consider the following code

class Thing 

    attr_reader :description 
    attr_writer :description 
    attr_writer :name 
    def initialize( aName, aDescription )             
        @name         = aName 
        @description  = aDescription 

    # get accessor for @name 
    def name 
        return @name.capitalize 


Here the Thing class explicitly defines a get method accessor for the @name attribute.

The get accessor, name, uses the String.capitalize method to return the string value of @name with its initial letter in uppercase.

When assigning a value to the @name attribute, there is no any special processing, so we have given it an attribute writer instead of a set accessor method.

The @description attribute needs no special processing at all, so we use attr_reader and attr_writer instead of accessor methods.

Ruby attribute is the equivalent of what many programming languages call a property.

To read and write a variable, use the attr_accessor method.

It provides a shorter alternative than using both attr_reader and attr_writer.

attr_accessor :value 

This is equivalent to the following:

attr_reader :value 
attr_writer :value 

Related Topic