Hi,

At 05:34 08/04/2004 +0900, you wrote:
What's the preferred way of accessing a class's instance variables?

I tend to use @var instead of self.var (I guess var() would work, and
var too).

I see two advantages:
   1) Faster (I never benchmarked however)
   2) Lines starting with @ are like methods with ! at the end =>
         Draw the attention to probable side effect on obj's state.

I do agree that typos can be an issue. There is warning however,
with ruby -w (that sometimes warns for some valid constructions
of mine, I guess defined? could help me avoid that).

Refering to a recent thread, I may add that self.var seems slightly
Python-ish.

I would personally prefer .var but languages with configurable style/
syntax are rare these days (missing C's #define).

Nota: Ruby let you add instance variables on the fly, such variables
default to nil. Maybe some "strict" pragma/hint would be welcome, paving
the way to some optimization where access to instance variables could
be direct versus thru an hash.

FWIW

Jean-Hugues

EOM

At 05:34 08/04/2004 +0900, you wrote:
>What's the preferred way of accessing a class's instance variables?
>Almost every example I've seen uses the @ form:
>
>class Test
>     def var_set
>         @var = 3
>     end
>     def var_modify(v)
>         @vare = 34
>         return @var
>     end
>end
>
>t = Test.new
>t.var_set
>puts t.var_modify
>
>The obvious problem with this can be seen in Test#var_modify.  The
>programmer meant to change the value of @var but made a typo and broke
>his code.  The program prints 3 instead of 34.
>
>The way around this is through accessors:
>
>class Test
>     attr_accessor :var
>     def var_set
>         self.var = 3
>     end
>     def var_modify
>         self.vare = 34
>         return self.var
>     end
>end
>
>This produces an error that can be caught.
>
>My question is this: why is this form so rarely used?  Is it the extra
>typing?  Is it somehow un-Rubyesque?  It seems like a good way to
>catch silly errors like the one above.
>
>Thanks,
>Bill

-------------------------------------------------------------------------
Web:  http://hdl.handle.net/1030.37/1.1
Phone: +33 (0) 4 92 27 74 17