Directly accessing an instance variable vs. Using an accessor method

独自空忆成欢 提交于 2019-11-27 09:15:25

问题


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


回答1:


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.




回答2:


"Accessing instance variable directly is about two times faster than accessing them with accessor methods"

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



来源:https://stackoverflow.com/questions/4639271/directly-accessing-an-instance-variable-vs-using-an-accessor-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!