Hi –
Jean-Hugues ROBERT jean_hugues_robert@yahoo.com writes:
Hi,
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:
- Faster (I never benchmarked however)
- Lines starting with @ are like methods with ! at the end =>
Draw the attention to probable side effect on obj’s state.
Don’t forget, though, that these techniques (@var vs. self.var) are
only equivalent in certain simple (and common, but not unique) cases.
If you’re doing anything more complex, like:
def var=(x)
@var = x.to_s.upcase
end
then you don’t have a choice; you have to go through the method
(self.var = y) rather than just doing @var = y, elsewhere in the
class.
(The original question involved another level of remove (wrapping the
attr_* methods themselves in “var_get” and “var_modify” methods, but
wherever they occur, @var = and self.var= are not automatically
equivalent.)
This also points to a constraint on Eric’s point about not wanting to
worry about forgetting the ‘self’ – namely, that you can only do that
when you know for sure that #var= is a simple set method for @var.
Also, the @var = y technique could come back to bite you if you
reimplement the setter method and haven’t routed your assignments
through it:
attr_accessor :var
def initialize(y)
@var = y # OK until you reimplement #var= to do something
end # non-simple, at which point you have to remember
# that you assigned directly to @var here.
(I would have quoted Eric directly except I’m posting directly to
comp.lang.ruby, because of the gateway problems, and Eric’s posts
don’t seem to be making it here 
David
···
At 05:34 08/04/2004 +0900, you wrote:
–
David A. Black
dblack@wobblini.net