Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.</p> <pre><code>class Person attr_accessor :age ... end </code></pre> <p>Here, I can see that I may both read and write the age.</p> <pre><code>class Person attr_reader :age ... end </code></pre> <p>Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.</p> <p>But what is happening behind the scenes?</p> <p>If you write:</p> <pre><code>attr_writer :age </code></pre> <p>That gets translated into:</p> <pre><code>def age=(value) @age = value end </code></pre> <p>If you write:</p> <pre><code>attr_reader :age </code></pre> <p>That gets translated into:</p> <pre><code>def age @age end </code></pre> <p>If you write:</p> <pre><code>attr_accessor :age </code></pre> <p>That gets translated into:</p> <pre><code>def age=(value) @age = value end def age @age end </code></pre> <p>Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload