Direct access to instance variable vs. Using access method

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

+77
ruby instance-variables accessor
Jan 09 '11 at 13:16
source share
2 answers

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

So basically these are two completely different things.

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

+97
Jan 09 2018-11-11T00:
source share

"Accessing an instance variable directly is about two times faster than accessing them using access methods"

Check out: http://greyblake.com/blog/2012/09/02/ruby-perfomance-tricks/

+1
Jan 12 '15 at 9:16
source share



All Articles