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

    @age

end

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.

 http://stackoverflow.com/questions/6337897/what-is-the-colon-operator-in-ruby

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

end

attr_accessor :age

just combines the two.

http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer 

and

http://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby?lq=1

Leave a Reply

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