Ruby: attr_accessor, attr_reader, attr_writer

Accessors are sometimes known as getters/setters or mutators.

They let you get/set instance variables.

In Ruby attr_reader, e.g.:

attr_reader :age

is equivalent to:

def age



Breaking it down – the :age is a symbol named “age”. Symbols have the feature that any two symbols named the same will be identical (they use the same pointer). 

This is not the same in a string.

This means comparing them is super fast – you just do a pointer comparison.

Also, symbols are immutable – again, not like strings.

So, writing attr_reader :age gets translated into code that returns the instance variable @age.

And, attr_writer :age gets translated to:

def age=(value)

  @age = value


attr_accessor :age

just combines the two. 


Leave a Reply

Your email address will not be published. Required fields are marked *