Have u ever find urself writing simple reader & writer like this:
1 2 3 4 5 6 7 8 |
|
You should probably be using Module#attr_accessor
:
1 2 3 4 5 6 7 |
|
If u want to keep the writer private, while still having the reader as public, you can do the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Besides Module#attr_accessor
, we also have Module#attr_reader
&
Module#attr_writer
, each generating just the reader/writer that u need.
Using the above accessor generators not only improve the readability of ur code, the generated accessors are also more performant. Here’s a quick benchmark:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
The difference is there, but it isn’t too much for just a pair of accessors. It would be more significant as the number of accessors increases. Anyway, i’ll leave it as an exercise for the reader.