Directly accessing an instance variable vs. Using an accessor method

后端 未结 2 1542
北恋
北恋 2020-12-12 13:13

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

相关标签:
2条回答
  • 2020-12-12 13:36

    "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 讨论(0)
  • 2020-12-12 13:42

    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.

    0 讨论(0)
提交回复
热议问题