Hi --

On Fri, 19 May 2006, Eli Bendersky wrote:

>
>> The behaviors provided by attr_* are implemented using instance
>> variables, but that's not the whole instance variable story.  I'm not
>> quite sure which constructs you're specifically thinking of, but if
>> you want your attr_* methods private, just do:
>>
>>    class C
>>      private
>>      attr_accessor :x
>>
>>      # etc.
>>    end
>>
>> The privacy you're gaining here is the privacy of the x and x=
>> methods.  That's separate from the fact that @x is "private" (i.e.,
>> only visible to the instance whose variable it is).  Even non-private
>> attr_*-generated methods use instance variables.  (Usually the point
>> is to make the object's state *less* private :-) too.
>
> Interesting - I didn't know that it's possible to have private variables
> by means of attr_* in 'private'. Thanks

You're actually getting private methods, not variables.  The methods
happen to use instance variables internally, but that's a separate
matter from their access level.

>>> My aim is to enhance the readability of my class. It won't affect its
>>> usage, just its comprehension when I return in the future trying to grok
>>> how it works.
>>
>> I don't think you'll get much clearer than:
>>
>>    @n = 1
>>
>
> Sure, the question is where to put this line. I find that when such
> "declarations" are interspersed in various methods of a 300-line class,
> it makes comprehension more difficult.

It's not really a declaration, though; it's just a variable
assignment.  Just put it somewhere before you need the variable to
have that value :-)


David

-- 
David A. Black (dblack / wobblini.net)
* Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
   > Ruby and Rails consultancy and training
* Author of "Ruby for Rails" from Manning Publications!
   > http://www.manning.com/black