O'Reilly logo

The Book of Ruby by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required