Directly accessing an instance variable vs. Using an accessor method

RubyInstance VariablesAccessor

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpistacchioView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - Rubymeso_2600View Answer on Stackoverflow