Directly accessing an instance variable vs. Using an accessor method

那年仲夏 提交于 2019-11-28 15:30:21
sepp2k

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: http://greyblake.com/blog/2012/09/02/ruby-perfomance-tricks/

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