80

Can anyone explain the difference between accessing an instance attribute via self.attribute and by @attribute?

2 Answers 2

99

self.attribute calls the method attribute.
self.attribute = value calls the method attribute= with the argument value.
@attribute and @attribute = value get/set the value of the instance variable @attribute.

So basically they're two entirely different things.

However if you call attr_accessor :attribute it defines the method attribute to return @attribute and the method attribute=(value) to set @attribute = value. So in that case, there is no difference.

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

2 Comments

Note that it is generally recommended to use self. (unless you're writing the getter/setter method) even if you currently have attr_accessor. This protects you from additional refactor work and bugs if you later change the accessor method(s) to do more than just get/set the instance variable. (Or if someone else patches or subclasses your work.)
One of the bugs Phrogz is talking about is if you simply call attribute = _____ instead of self.attribute = ______ you are setting a local variable instead of the instance variable.
3

"Accessing instance variable directly is about two times faster than accessing them with accessor methods"

Check out the: https://www.greyblake.com/blog/2012-09-01-ruby-perfomance-tricks/

1 Comment

The link is broken. This one works: greyblake.com/blog/2012-09-01-ruby-perfomance-tricks

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.