开发者

Directly accessing an instance variable vs. Using an accessor method

开发者 https://www.devze.com 2023-02-03 01:48 出处:网络
Can any开发者_Go百科one explain the difference between accessing an instance attribute via self.attribute and by @attribute?self.attribute calls the method attribute.

Can any开发者_Go百科one explain the difference between accessing an instance attribute via self.attribute and by @attribute?


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消