In general, I try to avoid using instance variables directly in Ruby. Using private accessor methods wherever possible accomplishes two things:
-
It makes it much easier to refactor down the line if you end up needing to add some additional behavior whenever a value is set (validation, callbacks, etc), because you need only add the
#my_attr=
method definition and need not find all the places where you used@my_attr = ...
and change them as well. -
It better guards against the kind of typo-induced bugs that leave one staring at their computer for half an hour cursing the day they decided to earn a living as a programmer. For example: