Cover by Huw Collingbourne

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Attribute Readers and Writers

In fact, there is a simpler and shorter way of creating a pair of get and set accessors simultaneously. All you have to do is use two special methods, attr_reader and attr_writer, followed by a symbol (a name preceded by a colon):

attr_reader :description
attr_writer :description

You should add this code inside your class definition like this:

class Thing
   attr_reader :description
   attr_writer :description
    # maybe some more methods here...
end

Calling attr_reader with a symbol has the effect of creating a get accessor (here named description) for an instance variable (@description) with a name matching the symbol (:description).

Calling attr_writer similarly creates a set accessor for an instance variable. Instance variables ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required