What do the attr_reader, attr_writer and attr_accessor messages do?

Just like in C#, in Ruby the access to the variables is set by setters and getters as oppose to methods getVar() and setVar(xx). These are usually defined like so:

This will simply return instance of the object "name" i.e. a getter.

Let's have a look at the example. In Ruby we have attr_reader:

Clearly, in the example above you are trying to assign a value to a variable which is only a getter. In order to set the value, we have a setter in the form of attr_writer:

We can write both: attr_reader and attr_writer.

But there is a shortcut attr_accessor.

Happy Coding

Leave Comment

Your email address will not be published.

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box