What’s the Ruby convention for referring to instance variables inside an instance method?
Consider the following variations:
def MyClass
attr_accessor :q
def initialize(z)
@q = z
end
def method_one
puts q
end
def method_two
puts @q
end
def method_three
puts self.q
end
end
Which convention q, @q or self.q is preferred?
The whole reason that Ruby uses instance variables and accessor methods (with syntax sugar to look like you’re getting direct access to properties) is so that you can refactor your classes and external consumers of your interface
don’t have to know if you internally have:
or
This same rational applies equally well to your own code. If you have a class with 100 methods that all reference your
@minutes, and then you decide that you really should be storing@secondsyou will need to change 100 methods. On the other hand, if you had usedminutes(your “method_one”) instead, none of your methods would need to change.There is a small performance hit for using the method-invocation notation instead of directly accessing the instance variable. If speed is critical you may want to consider direct access; otherwise, I encourage you to eat your own dog food and use any publicly-accessible interfaces you expose, when they exist.
And, as @Alex answered, you must use the
self.foo = 42notation when invoking a ‘setter’ method, asfoo = 42will always set a local variable instead.