Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly accessing an instance variable vs. Using an accessor method

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

like image 972
pistacchio Avatar asked Jan 09 '11 13:01

pistacchio


People also ask

What's the difference between methods and instance variables?

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".

What is the purpose of an accessor method?

An accessor method is an instance method that gets or sets the value of a property of an object.

Is it possible to access instance variables and methods without using objects?

Class methods cannot access instance variables or instance methods directly—they must use an object reference.

Are accessor methods instance methods?

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.


2 Answers

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.

like image 128
sepp2k Avatar answered Nov 01 '22 04:11

sepp2k


"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/

like image 32
meso_2600 Avatar answered Nov 01 '22 04:11

meso_2600