Can anyone explain the difference between accessing an instance attribute via self.attribute and by @attribute?
Asked
Active
Viewed 1.2k times
80
sawa
- 160,959
- 41
- 265
- 366
pistacchio
- 53,670
- 101
- 270
- 404
2 Answers
100
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.
Peter Lang
- 52,486
- 27
- 146
- 157
sepp2k
- 353,842
- 52
- 662
- 667
-
14Note 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.) – Phrogz Jan 09 '11 at 15:03
-
6One 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. – Jason Noble Apr 04 '12 at 05:48
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/
meso_2600
- 1,708
- 2
- 21
- 45
-
1The link is broken. This one works: https://www.greyblake.com/blog/2012-09-01-ruby-perfomance-tricks/ – nbkhope Mar 09 '20 at 16:06