Can anyone explain the difference between accessing an instance attribute via self.attribute
and by @attribute
?
An object that belongs to a class is said to be an instance of that class. The variables that the object contains are called instance variables. The subroutines that the object contains are called instance methods. (Recall that in the context of object-oriented programming, method is a synonym for "subroutine".
An accessor method is an instance method that gets or sets the value of a property of an object.
Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Accessor methods, also called get methods or getters, allow a way to get the value of each instance variable from outside of the class. In the next lesson, we will see mutator methods, also called set methods or setters, that allow a way to change the values of the instance variables.
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.
"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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With