假设我有一个类,我在其中定义了一个 attr_accessor
,如下所示:
private
attr_accessor :attribute
我理解为什么使用 self.attribute
读取器方法不起作用 - 在 Ruby 中,您不能在显式接收器上调用私有(private)方法。
令我困惑的是,为什么这条规则不适用于作者?为什么我可以调用 self.attribute = 1
,并且不会引发任何访问冲突错误?
最佳答案
根据@Jörg W Mittag 对 Alan Skorkin 博客条目的评论 Ruby Access Control – Are Private And Protected Methods Only A Guideline? :
Quick note: there is a special case where calling private methods with an explicit receiver is allowed:
If the method name ends with '=' (i.e. it is an attribute writer) and the explicit receiver is 'self', then this works. This is necessary, because setters can only be called with an explicit receiver because of the method/variable ambiguity. Otherwise it wouldn't be possible to call private setters.
Jörg 没有引用任何消息来源,但他非常可靠。
关于ruby - 使用私有(private) attr_accessor 时,为什么 self.attribute= 起作用,而 self.attribute 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701663/