B
Bill Atkins
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
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