2

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?

1

2 Answers 2

4

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

puts musicObj.minutes

don't have to know if you internally have:

attr_accessor :minutes

or

def minutes
  @seconds / 60.0
end

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 @seconds you will need to change 100 methods. On the other hand, if you had used minutes (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 = 42 notation when invoking a 'setter' method, as foo = 42 will always set a local variable instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Good point (+1). But your example sucks a bit. If you only use the accessors, self.minutes= in your example will just store seconds with a resolution of 60 :-)
@undur_gongor Not if you pass in a float number of minutes; e.g. def minutes=(m); @seconds = (m*60).round; end
3

self.q is used when setting the variable

self.q = 'Some value.'

whereas q is used when getting the variable

puts q
do_something_with_variable(q)

Of course, these are purely conventions. You can substitute self.q for q when getting the variable whenever you like (although consistency is recommended).

I find this discussion quite enlightening with regards to using @q.

2 Comments

@q seems to work when setting the variable in initialize. Is self.q required?
@MrMusic: @q works for setting too. After all, that's the instance variable itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.