Hi --

On Fri, 19 May 2006, Eli Bendersky wrote:

> Hello fellow Rybuists,
>
> One thing I like about C++'s OO is the way in which all class & instance
> variables are conveniently "declared" in respective public and private
> sections. This makes the code easier to understand, since the
> declaration is a good place to comment on the variable, explaining how
> it is used.
>
> Ruby has several options regarding this, but nothing of a concensus, it
> seems. Public members can be declared with 'attr' and friends. But what
> about private memberes. For now I find it convenient to preallocate
> those in 'initialize'. What are the approaches you use ?

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 :-)

You can always just use an instance variable on its own, too.

> 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


:-)

-- 
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